2015-05-31 46 views
-2

2000000以下所有素數的總和是多少?低於10總和 實施例是2 + 3 + 5 + 7 = 17歐拉項目10練習

我寫這個代碼,但仍然得到錯誤的答案: 我測試超過幾百較低的數字,它已示出的正確答案。

#include <iostream> 
#include <math.h> 
using namespace std; 

bool isPrime(long n) 
{ 
    if (n < 2) 
     return false; 
    if (n == 2) 
     return true; 
    if (n == 3) 
     return true; 
    int k = 3; 
    int z = (int)(sqrt(n) + 1);  // square root the n, because one of the product must be lower than 6, if squared root of 36 

    if (n % 2 == 0) 
     return false; 
    while (n % k != 0) 
    { 
     k += 2; 
     if (k >= z) 
      return true; 
    } 
    return false; 
} 

long primeSumBelow(long x) 
{ 
    long long total = 0; 
    for (int i = 0; i < x; i++)   // looping for times of prime appearing 
    { 
     if (isPrime(i) == true) 
      total += i; 
     if (isPrime(i) == false) 
      total += 0; 
    } 
    cout << "fd" << endl; 
    return total; 
} 

int main() 
{ 
    cout << primeSumBelow(20) << endl; 
    cout << primeSumBelow(2000000) << endl; 

    system("pause"); 
    return 0; 
} 
+0

我想你只是忘記了求和函數的返回類型中的「long」 - 總和比適合於有符號32位整數的值大60倍,並且你的局部變量具有不同的類型。 – molbdnilo

回答

0

total計數器的類型是正確long long。不幸的是,函數primeSumBelow僅返回long,因此,根據平臺,正確計算的結果在從此函數返回時會被截斷。