c++ - 错误的输出 - Ramanujan 对阶乘和 C++ 的近似

标签 c++ factorial

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

int main()
{

    int n, k, g;
    float fact;

    cin >> n;

    fact = sqrt(3.14159265359)*pow(n/2.7182818284, n);
    fact *= pow(((8*n + 4)*n + 1)*n + (float)1/30, (float)1/6);

    k=floor(fact);

    g=k%1000000000;

    cout << g << "\n";
    
};

我的程序计算 n 的值!模 1000000000。对于较小的 n 值,它工作得很好。但对于较大的,它会不断输出 -147483648。我的代码有什么问题?

最佳答案

这是变量 fact 的溢出问题,您超出了 float 可以容纳的最大值。

实际上,像 long doublelong long int 这样更大的类型将无法容纳这些巨大的值,您需要更大的类型。

我建议通过循环 1 到 n 来解决它,在每次迭代时相乘并应用 mod。这将使数量保持较小。

Ramanujan 的阶乘近似在这里对你没有帮助,因为它没有考虑 mod 优势,你可以试试 Wilsom Theorem

关于c++ - 错误的输出 - Ramanujan 对阶乘和 C++ 的近似,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34376245/

相关文章:

c# - 什么是 __int32?

C++ 外部对象放置

c++ - 错误 C2660 : 'Aba::f' : function does not take 0 arguments

阶乘的精度运算和溢出

c++ - CMake:子目录可以继承编译特性吗?

c++ - C++ 中的链接错误 - 实现 indexList

使用 for 循环的 Java 阶乘代码未显示准确的输出

在 C 中计算阶乘会导致错误的答案

c - 如何计算x的阶乘

java - 指数 b 中的最后一位数字