Search code examples
c++codeblocksxterm

Error while solving Project Euler sum number 3 in C++


This is my code :

#include <iostream>

using namespace std;

int main()
{
    long int x = 1;
    long int res;

    while (x<600851475143)
    {
        x++;
        if(600851475143%x==0)
        {
            res=x;
            cout<<x<<"\n";
        }
    }
}

I don't know whats wrong with it but it gives me this output :

839
1471
6857
59569
104441
486847
1234169
5753023
10086647
87625999
408464633
716151937
-716151937
-408464633
-87625999
-10086647
-5753023
-1234169
-486847
-104441
-59569
-6857
-1471
-839
-71
-1
Floating point exception

Process returned 136 (0x88)  execution time : 156.566 s
Press ENTER to continue.

and when i substitute 600851475143 with 13195 [ which was in the example ]... it works fine...and gives me this output :

5
11
55
11149

Process returned 0 (0x0) execution time : 0.005 s
Press ENTER to continue.

I don't know what i am doing wrong... :/ Perhaps my previous program didn't run properly...i tried it with int in the beginning and then changed it to long int...No difference...


Solution

  • Negative values are due to overflow. Start by using unsigned integers instead of signed integers. In addition to that, in 32 bit computers, long int and int types are both 32 bits.

    unsigned long long int x = 1;
    unsigned long long int res;
    

    Also, you could emphasize the fact that those constants are unsigned

    while (x<600851475143U)
        {
            x++;
            if(600851475143U%x==0)
            {
                res=x;
                cout<<x<<"\n";
            }
        }