为什么这个C ++主要检查器和夏天会返回错误的结果?

时间:2017-04-10 13:25:30

标签: c++ fizzbuzz

我不明白为什么总和永远不会正常,但总结一致。 它会抛出任何错误,但永远不会得到正确的结果。根据wolfram | alpha,我可以使用多达200亿的大型计算。我不知道为什么会这样,所以你可能有任何想法都非常感谢! 注意:使用-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

1 个答案:

答案 0 :(得分:1)

在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;
}

除非我误解了什么。