Question

I was working on the following problem from Project Euler.

What is the largest prime factor of the number 600851475143?

I have come up with the following solution.

#include<iostream>
#include<cstdlib>
#include <limits>
#include <math.h>
 /**Project Euler:What is the largest prime factor of the number 600851475143**/
using namespace std;
bool isPrime(int n){
    int sq,a=2;
    sq=sqrt(n);
    while(a<sq)
    {
        if(n%a==0)
            return false;
    }
    return true;
}
int main() {
int c=2,max_prime;
long long d=600851475143;
int e=sqrt(d);
while(c<e)
{
    if(isPrime(c))
    {
            if(d%c==0)
                max_prime=c;
    }
c++;
}
cout<<max_prime;
    return 0;
}

There is no compilation error in the program but it is taking a lot of time in running. I have looked at other solutions but am not able to find out the mistake in my solution.I suspect there is something wrong because of the large number involved. What could that be? Any help appreciated.

Was it helpful?

Solution

Your isPrime function never increments a, so you're in an endless loop there.

OTHER TIPS

In your isPrime method you're not changing any of the variables that control the while condition within the body of the while statement, so the loop wil run forever.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top