C++代码输出负值

C++ code outputting negative values

本文关键字:输出 代码 C++      更新时间:2023-10-16

我为一个谜题类型的网站写了一个解决方案。在具有最新g ++的XCode上,我的代码编译良好。在他们的网站(和代码板(上,我的输出是负数。有人可以帮助我理解为什么,因为我真的被难住了。

#include <iostream>
#include <cmath>
#include <vector>
#include <map>
using namespace std;
vector<int> getAllPrimes(vector<int> primesArray, int n)
{
    vector<int> numArray (n+1, 1);
    for (int i = 2; i <= n; i++)
    {
        if (numArray[i] == 1)
        {
            primesArray.push_back(i);
            for (int k = i; k <= n; k+= i)
            {
                numArray[k] = 0;
            }
        }
    }
    return primesArray;
}
int main()
{
    long n = 32327;
    if (n == 1)
    {
        printf("%ldn", n);
        return EXIT_SUCCESS;
    }

    map <int, int> primeMap;
    map <int, int>::iterator itr;
    vector<int> primesArray;
    primesArray = getAllPrimes(primesArray, n);
    while(!primesArray.empty())
    {
        long currPrime = primesArray.back(), curr = currPrime;
        while (currPrime <= n)
        {
            primeMap[curr] += (int)floor(n/currPrime);
            currPrime *= curr;   //multiply currPrime to add another factor of curr. 
        }
        primesArray.pop_back();
    }
    //get the number of divisors of n!
    long numDivisors = 1;
    for (itr=primeMap.begin(); itr != primeMap.end(); itr++)
    {
        numDivisors *= ((*itr).second*2)+1;     //power of each prime + 1, * 2 because you need the number of divisors of the square of n!
        numDivisors = numDivisors % 1000007;
    }
    printf("%ldn", numDivisors);
    return 0;
}

通常"long n"应该从标准输入中读取 1 到 100 万之间的整数,但我只是分配了一个值来模拟它。

我在这里将代码放在代码板中:http://codepad.org/RpPFuLzX。如您所见,输出是 -596936 ,而在我的机器上它是656502(这是正确的输出(。到底是怎么回事?

很可能是 CodePad 和其他站点在 32 位系统上编译,其中long长度为 4 字节 (http://codepad.org/W00vCFIN(。在OS X上,所有内容默认为64位,在这些系统(但不是Windows(上,long为8字节长。因此,您在某个时候溢出了计算。

如果依赖于特定的整数大小,请使用 stdint.h

这是一个改编版本,它符合您的预期输出,使用int64_t: http://codepad.org/Owsl3ClR

您获得不同结果的原因是,像 long 这样的数据类型在 32 位和 64 位上的处理方式不同。Mac OS X 使用 LP64 数据模型,其中 long 在 64 位模式下为 64 位,在 32 位模式下为 32 位。如果分别为 32 位和 64 位构建程序,您将看到不同的结果。

一种流行的解决方案是使用指定位数的数据类型,例如uint64_t用于大小为 64 位的无符号整数,而不是根据标准刚好等于或大于 intlong

在线粘贴到科莫,我得到:

"ComeauTest.c", line 49: error: more than one instance of overloaded function
          "floor" matches the argument list, the choices that match are:
            function "floor(long double)"
            function "floor(float)"
            function "floor(double) C"
            function "std::floor(long double)"
            function "std::floor(float)"
            The argument types that you used are: (long)
              primeMap[curr] += (int)floor(n/currPrime);