Question

I am attempting to solve Project Euler problem 10 where the user is asked to calculate the sum of all the primes less than two million. I've written the following by studying the pseudocode on Wikipedia but the answer it generates seems to be incorrect, at least according to the website whenever I try to enter it:

int main()
{
   int limit = 2000000;
   int answer = 5;

   std::vector<bool> isPrime;
   for( int i = 0; i < limit; ++i ){
      isPrime.push_back( false );
   }

   int n = 0;
   for( int x = 1; x <= ceil( sqrt( limit ) ); ++x ){
      for( int y = 1; y <= ceil( sqrt( limit ) ); ++y ){

         n = 4*x*x + y*y;
         if( (n <= limit) && ( n%12 == 1 || n%12 == 5 ) ){
            isPrime.at(n) = ! isPrime.at(n);
         }

         n = 3*x*x + y*y;
         if( (n <= limit) && ( n%12 == 7 ) ){
            isPrime.at(n) = ! isPrime.at(n);
         }

         n = 3*x*x - y*y;
         if( (x > y) && (n <= limit) && (n%12 == 11) ){
            isPrime.at(n) = ! isPrime.at(n);
         }
      }
   }

   for( n = 6; n <= ceil( sqrt( limit ) ); n += 2 ){
      if( isPrime.at(n) ){
         for( int m = n*n; m < limit; m += n*n ){
            isPrime.at(m) = false;
         }
      }
   }

   for( int i = 5; i < limit; i += 2 ){
      if( isPrime.at(i) ){
         answer += i;
      }
   }

   std::cout << "The sum of the primes below " << limit << " is " << answer << std::endl;

   return 0;
}

The following output is generated:

The sum of all the primes below 2000000 is 1179908154

I've tested it with smaller limits that I'm able to verify by hand and the code is indeed functioning correctly for those numbers. I've found other peoples implementation which indicate that the answer should be 142913828922, but I can't figure out where their code differs from mine.

Can anyone see what it is I'm doing wrong here?

Was it helpful?

Solution

You only have a signed 32-bit integer for the answer. The actual answer is much higher than can fit in 32 bits, so you have to go over to using 64 bit integers. Try using unsigned long long instead.

OTHER TIPS

You can create your own class to store big numbers.Or u can use an array of integer to store your answer and storing each digit at each index. (Even if unsigned long long not working) :)

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