Q:Find the sum of all the primes below two million.
Sol:
The logic used to solve the problem was the same as in problem 7 of finding the nth prime.
Code for the problem is also very similar,the small difference being finding the sum.
#include<cstdio>
#include<cmath>
using namespace std;
int main()
{
int n;
scanf("%d",&n);
int arr[500000];
int i=2;
arr[0]=2;
arr[1]=3;
int k=1,j;
long long sum=5;
int nextprime,flag=0,c=1;
nextprime=5;
while(nextprime<n)
{
flag=0;
for(j=0;((j < i)&&(arr[j]<=sqrt((double)nextprime)));j++)
{
if(nextprime%arr[j] == 0)
{
flag=1;
break;
}
}
if(flag==0)
{
arr[i]=nextprime;
if (arr[i]< n)
sum=sum+(long long)(arr[i]);
i++;
}
if(c==-1)
k++;
nextprime=6*k +c;
c=-c;
}
printf("%lld\n",sum);
}
The program takes 2-3 seconds to execute for the value of n being two million.
Please post your comments and doubts.
Suggestions for better algorithms are always welcome :)
Thursday, October 7, 2010
Subscribe to:
Comments (Atom)