mercredi 28 juin 2017

My Project Euler code for #3 works for random numbers I test but gives 3 for 600851475143

Spoilers if you haven't done PE #3

 #include <iostream>
using namespace std;

This function tests for primes

long long isPrime(long long n)
{
    if (n % 2 == 0)
    {
        return 0;
    }
    for (int i=3; i<sqrt(n)+1; i+=2)
        if (n % i == 0)
        {
            return 0;
        }
    return 1; 
}

This one returns the biggest prime.

long long maxPrime(long long n)
{
    int max=3;
    for (int i=3; i<n+1; i+=2)
     if ((isPrime(i)==1)&&(n%i==0))
     {
         max = i;
     }
    return max;
}

This one gives the answer.

int main()
{
    int q;
    cin >> q;
    cout << maxPrime(q) << endl;



}

I have no idea why it does that. I am fairly certain my isPrime() function works and this works for smaller numbers but not 600851475143. For 600851475143, it gives 3. But for random numbers like 12321 it correctly gives 37 and the example, 13195, it correctly gives 29.

Aucun commentaire:

Enregistrer un commentaire