Project Euler Problem 10

版权声明:代码属于原创,转载请联系作者并注明出处。 https://blog.csdn.net/weixin_43379056/article/details/83010205

Problem 10 : Summation of primes

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

Find the sum of all the primes below two million.

#include <iostream>
#include <cstring>   // memset()
#include <ctime>     // clock()
#include <cmath>     // sqrt()
#include <cassert>   // assert()

using namespace std;

class PE0010
{
private:
    static const int m_MAX = 2000000; // two million
    bool *m_Sieve;  // Prime Sieve

public:
    PE0010() { m_Sieve = new bool [m_MAX+1]; }
    ~PE0010() { delete [] m_Sieve; }

    void createPrimeSieve();
    long long getSumOfPrimes(int number = m_MAX);
};

// create a prime Sieve of Eratosthenes below max value
void PE0010::createPrimeSieve()
{
    memset(m_Sieve, true, (m_MAX+1)*sizeof(bool)); 

    m_Sieve[0] = m_Sieve[1] = false;

    for (int i=2; i<=(int)sqrt((double)m_MAX); i++) 
    {
        if (true == m_Sieve[i]) 
        {
            for (int j=i*i; j<m_MAX; j+=i)
            {
                m_Sieve[j] = false;
            }
        }
    }
}

// calculate sum of all primes below number
long long PE0010::getSumOfPrimes(int number)
{
    long long sum = 2;  // first prime prime is 2

    for (int n=3; n<number; n+=2) // primes above 2 are odd 
    {
        if (true == m_Sieve[n])
        {
            sum += n;
        } 
    }
        
    return sum;
}

int main()
{
    clock_t start = clock(); 

    PE0010 pe0010;

    pe0010.createPrimeSieve();

    assert(17 == pe0010.getSumOfPrimes(10));
    
    cout << "The sum of all the primes below two million is " ;
    cout << pe0010.getSumOfPrimes() << endl;

    clock_t finish = clock();
    double duration=(double)(finish - start) / CLOCKS_PER_SEC;
    cout << "C/C++ application running time: " << duration << " seconds" << endl;

    return 0;    
}

猜你喜欢

转载自blog.csdn.net/weixin_43379056/article/details/83010205
今日推荐