Hey, guys.
Find the sum of all the primes below 2000000.
My code:
main.cpp
#include <iostream>
#include <vector>
#include <cmath>
#include "Sieve.h"
using namespace std;
typedef unsigned long long int ulli;
ulli Sum = 0;
ulli Sum_of_Primes(vector<bool>, ulli&);
ulli Sum_of_Primes(vector<bool> Primes, ulli& Sum)
{
for(ulli a = 2; a < Upper_Limit; a++)
{
if (Primes[a])
{
Sum += a;
}
}
return Sum;
}
int main()
{
Find_Primes_until_n(Primes);
cout << Sum_of_Primes(Primes,Sum) << endl;
return 0;
}
Sieve.h
#ifndef SIEVE_H_INCLUDED
#define SIEVE_H_INCLUDED
using namespace std;
#define Upper_Limit 2000000
vector<bool> Primes;
void Find_Primes_until_n (vector<bool>&);
void Find_Primes_until_n(vector<bool>& Primes)
{
Primes.resize(Upper_Limit);
fill(Primes.begin(),Primes.begin() + Upper_Limit , true);
for (int i = 2; i < Upper_Limit; i++)
{
if(Primes[i])
{
for (int j = 2*i; j <Upper_Limit; j+= i)
{
Primes[j] = false;
}
}
}
}
#endif // SIEVE_H_INCLUDED
It takes about 0.3s. How can I improve it?
Thank you.
Petcheco