开发者

Confusing solution for problem 10 in projecteuler

I solved problem 10 in project euler (but my solution took 2000 seconds), so I tried to find faster solution. I found this (execution time 0.1 sec), but I don't understand this solution and I need help.

#include <stdio.h>
#include <string.h>
#include <math.h>
using namespace std;
#define HIGHEST 2000000

char Prime[HIGHEST / 2];

int main(int argc, char** argv)
{
   unsigned int i, j;
   unsigned long long sum = 2;
   unsigned int total = 0;

   /* Set entire array to true (prime) */
   memset(Prime, 1, sizeof(char)*HIGHEST / 2);
   /* except for 1 */
   Prime[0] = 0;

   for(i = 3; i < HIGHEST; i += 2) {
      if(Prime[i / 2] == 1) {
         sum += (unsigned long 开发者_JAVA百科long)i;
         total++;
      }
      for(j = (i+i+i)/2; j < HIGHEST/2; j += i) {
         Prime[j] = 0;
      }
   }
   printf("Sum: %llu (%d prime numbers)\n", sum, total);
   return 0;
}


The solution is a somewhat strange version of the Sieve of Eratosthenes. It looks like the writer was trying to prematurely optimise by doing some sneaky tricks with the loop counter, i.

I suggest that you work through the first few iterations of the loop on paper to get a feel for what the code is doing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜