Sum of prime numbers below 2 million - Optimization?
Mar 29, 2014 at 1:27pm UTC
Hi, this is my attempt to calculate the sum of all prime numbers bellow 2000000.
Even though it's kinda fast (took about 6.5 seconds in Code::Blocks) I was wondering how could it be optimized.
Also, what's your opinion on my attempt?
Thanks in advance!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iostream>
#include <math.h>
using namespace std;
bool isPrime(int );
long long primeSum=1;
int main()
{
for (int n=1; n<2000000; n+=2){
if (isPrime(n)==true ) primeSum+=n;
}
cout << primeSum;
}
bool isPrime(int num)
{
for (int d=1; d<=sqrt(num); d+=2){
if (num%d==0 and d!=1){
return false ;
}
}
return true ;
}
Mar 29, 2014 at 3:00pm UTC
Have you turned on compiler optimizations?
For me your program runs in 1.1 seconds without compiler optimizations (-O0) and in 0.6 seconds with optimizations turned on (-O2).
Mar 29, 2014 at 9:04pm UTC
Well, I thought that it was already optimized xD.
But I changed the settings and it took 0.37 seconds (-O2)!
Thanks!
Topic archived. No new replies allowed.