Finding Prime Numbers Using C++
#include <string>
using namespace std;
void main()
{
int max;
cin> > max;
if(max <= 0)
{
cout<<"Please enter a digit> 0\n";
}
int* primes;
int primecount = 0;
//allocate enough memory for primes
primes = new int[((int)(max/2)) + 1];
primes[0] = 2;
primecount++;
//count by 2s because evens cant be prime
//(except 2, which we give for "free")
for(int p = 3; p <= max; p+=2)
{
//if a number is divisible by a prime, it is not prime
for(int i = 0; i < primecount; i++)
{
if(p%primes[i]==0)
{
break;
}
//if the we’ve passed the point in the list where a
//prime is larger than half of our
//prime candidate, we definately have a prime
if( (primes[i])> (p/2) )
{
primes[primecount++] = p;
goto nextcandidate;
}
}
nextcandidate: ;
}
//Display max prime
cout << primes[primecount-1] << endl;
delete [] primes;
cin >> max;
}