Problem 10

Statement
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

Solution
The code, in C.

#include <stdio.h>

unsigned long long int primeSum(int l)
{
  int a[l+1];
  unsigned long long int b,c;
  unsigned long long int s=0;
  for(b=0;b<=l;b++)
    a[b]=1;
  a[0]=0;
  a[1]=0;
  for(c=2;c<1800;){
    for(b=c+1;b<=l;b++)
      if(b%c==0) a[b]=0;
    for(b=c+1;b<=1800;b++){
      c=l;
      if(a[b]==1){
	c=b;
	break;
      }
    }
  }
  for(b=0;b<=l;b++)
    if(a[b])
      s+=b;
  return s;
}

int main(void)
{
  printf("%llu\n",primeSum(2000000));
  return 0;
}

Answer
142913828922

No tags for this post.
  • http://www.lesena-hisa.net Blaz

    Very nice done. But I managed to do a lot easier with PHP.