#include <iostream>
int main()
{
usingnamespace std;
int x = 600851475143; // value to study
int nAllPrime = 1; //will multiply unti reach x
int nPrime = 0; // largest prime found
for ( int nPrimeF = 2 ; x > nAllPrime ;)
if ((x % nPrimeF) == 0)
{
x / nPrimeF ;
nAllPrime *= nPrimeF;
{
if(nPrime < nPrimeF)
nPrime = nPrimeF;
}
nPrimeF = 2;
}
elsereturn ++nPrimeF;
cout << nPrime << endl;
system("pause");
return 0;
}
in line 12, this condition means your number was evenly divisible by nPrimeF, and is therefore not a prime number. If it's not divisible, then it's a possible prime number, but you then immediately increment it and return the result.
First, the number you start with is too large to fit in an int, so this is not going to work.
Given the initial values this is what will happen:
line 12: is there a remainder from 600851475143 / 2 -> yes
line 22 - 23: there is a remainder so return 3
The code will jump from line 12 to line 22, and it will never get beyond line 23
Well, I think there's a problem with the logic, and it's one thing to write legal code, it's another thing to write code that gives the results you expect. I don't quite follow the logic as expressed in the code above, but then the code was obviously not doing what you wanted, so it probably wan't expressing your logic properly anyway.
Could you explain in human language or pseudo-code, the algorithm you're trying to implement?
Also clarify the actual question:
Are you trying to find the biggest prime number smaller than that number above?
Are you trying to find the biggest prime factor of that number above?
I show some code below, assuming you want the biggest prime factor. I have delibrately used brute force methods, which are extremely inefficient. It's up to you to supply your own algorithms and make it run more quickly.
#include <iostream>
#include <vector>
usingnamespace std;
typedefunsignedlonglong ull_t;
bool is_prime(ull_t num);
int main()
{
ull_t x = 600851475143;
ull_t div = 2;
vector<ull_t> factors;
while (div <= (x / 2))
{
if (0 == (x % div))
{
// x is divisible by div so div is a factor
factors.push_back(div);
}
++div;
}
if (factors.empty())
{
// x is prime, let's go through the motions anyway for symmetry
factors.push_back(x);
}
// factors is already sorted so starting at the end starts with the biggest value
vector<ull_t>::const_iterator ci = factors.end();
while (ci != factors.begin())
{
--ci;
// *ci is the biggest factor
if (is_prime(*ci))
{
// *ci is a prime number
cout << "biggest prime factor of " << x << " is " << *ci << endl;
break;
}
}
}
bool is_prime(ull_t num)
{
for (ull_t div = 2; div < num; ++div)
{
if (0 == (num % div))
{
returnfalse;
}
}
returntrue;
}