为什么这个 C++ 素数检查器和 summer return 的结果是错误的?

Why does this C++ prime checker and summer return wrong results?

我不明白为什么求和总不能正常工作,但求和始终如一。 它不会抛出任何错误,但永远不会得到正确的结果。根据 wolfram|alpha,对于大型计算,我可以关闭多达 20 000 000 000。我不知道为什么会这样,所以非常感谢您的任何想法! 注意:使用 -O3 和 -std=c++14 标志编译。

代码:

#include "stdafx.h"
#include <math.h>
#include <vector>
#include <stdio.h>
#include <iostream>
typedef unsigned long long ul;
const ul PRIMES = 1000000;
bool isPrime(ul n)
{
    if (n <= 1) return false;
    double sqN = sqrt(n);
    for (ul i = 3; i <= sqN; i++) {
        if ((int)n % i == 0) return false;
    } return true;
}
int main()
{
    std::vector<ul> primes;
    ul sumPrimes = 0;
    ul numPrimes = 0;
    for (ul n = 2; n <= PRIMES; n++) if (isPrime(n)) primes.push_back(n);
    numPrimes = primes.size();
    for (ul sp : primes) sumPrimes += sp;
    std::vector<ul> fizz, buzz, fizzbuzz;
    ul sumF = 0, sumB = 0, sumFB = 0;
    ul numF = 0, numB = 0, numFB = 0;
    for (ul prime = 0; prime < primes.size(); prime++) {
        if (prime % 15 == 0) {
            fizzbuzz.push_back(primes[prime]);
        }
        else if (prime % 5 == 0) {
            buzz.push_back(primes[prime]);
        }
        else if (prime % 3 == 0) {
            fizz.push_back(primes[prime]);
        }
    }
    for (ul fb : fizzbuzz) sumFB += fb;
    for (ul f : fizz) sumF += f;
    for (ul b : buzz) sumB += b;
    numF = fizz.size(); numB = buzz.size(); numFB = fizzbuzz.size();
    std::cout << "Stats for primes upto\t" << PRIMES << "\n";
    std::cout << "Primecount:\t\t" << numPrimes << "\n";
    std::cout << "Sum Primes:\t\t" << sumPrimes << "\n";
    std::cout << "Fizzcount:\t\t" << numF << "\n";
    std::cout << "Sum Fizz:\t\t" << sumF << "\n";
    std::cout << "Buzzcount:\t\t" << numB << "\n";
    std::cout << "Sum Buzz:\t\t" << sumB << "\n";
    std::cout << "FizzBuzzcount:\t\t" << numFB << "\n";
    std::cout << "Sum FizzBuzz:\t\t" << sumFB << "\n";
    std::system("pause");
    return 0;
}

这是我得到的输出: output

在您的 isPrime 方法中,您从 i = 3 开始。从 i = 2 开始,这样您将删除因数为 2 的非素数。

bool isPrime(ul n)
{
    if (n <= 1) return false;
    double sqN = sqrt(n);
    for (ul i = 3; i <= sqN; i++) {
        if ((int)n % i == 0) return false;
    } return true;
}

尝试

bool isPrime(ul n)
{
    if (n <= 1) return false;
    double sqN = sqrt(n);
    for (ul i = 2; i <= sqN; i++) {
        if ((int)n % i == 0) return false;
    } return true;
}

除非我误解了什么。