I just wrote the following to utilize the sieve to find the largest prime factor of some natural number greater than 2.
The program builds and runs and works for small test values, but simply crashes for values larger than, say, 1000000.
I wrote this myself--and believe it will probably be extremely inefficient--after finding out what the sieve is about.
Can you please suggest improvements?
Thank you.
//LARGEST PRIME FACTOR w/SIEVE OF ERATHOSTHENES
#include <iostream>
#include <math.h>
using namespace std;
unsigned long long int numberToCheck=0;
void sieve(unsigned long long int checkNumber)
{
checkNumber=numberToCheck;
unsigned long long int root=(int)(sqrt(checkNumber));
unsigned long long int primeFlagger[checkNumber+1];
for(unsigned long long int i=0;i<=checkNumber;i++)
{
primeFlagger[i]=1;
}
primeFlagger[0]=0;
primeFlagger[1]=0;
for(unsigned long long int j=2;j<=checkNumber;j++)
{
if(primeFlagger[j]==1)
{
for(unsigned long long int k=2;(k*j)<=checkNumber;k++)
{
primeFlagger[j*k]=0;
}
}
}
for(unsigned long long int l=checkNumber;l>=0;l--)
{
if(primeFlagger[l]==1)
{
if(checkNumber%l==0)
{
cout<<l<<" is the largest prime factor"<<endl;
break;
}
}
}
}
int main()
{
cout<<"Largest prime factor less then or equal to? "<<endl;
cin>>numberToCheck;
cout<<endl;
cout<<"Retrieving largest prime factor..."<<endl;
sieve(numberToCheck);
return 0;
}