【问题标题】:Unable to have 100 factorial with C++ on output screen(displaying 0)无法在输出屏幕上使用 C++ 进行 100 阶乘(显示 0)
【发布时间】:2022-01-25 21:22:01
【问题描述】:

好吧,我在这个问题上停留了很长一段时间:

问题: 要求您计算一些小的正整数的阶乘。


输入:

一个整数t,1


输出:

对于输入时给定的每个整数 n,显示值为 n 的一行!

//coded in c++
#include <bits/stdc++.h> //loadind up all the libraries at once.
using namespace std;

int main()
{   int T;
    scanf("%d", &T); 

//I am not doing "cin<<" cause "scanf" is faster than it

    for (int i = 0; i < T; i++)
    {
        int N;
        scanf("%d",&N);
        long long int product = 1;
        while (N >0){
            product = product * N;
            N--;
        }
        printf("%lld\n",product);
    }    
    return 0;
}

我能得到 10!,20!但无法获得100! (阶乘) 所以极端情况不满足。请帮我为我的变量获得一个好的数据类型为 100!阶乘的位数超过 100 位。当我在终端上输入 100 时它显示 0。

P.S - 这个问题来自 CodeChef 网站 (FCTRL2)。

【问题讨论】:

  • #include &lt;bits/stdc++.h&gt; using namespace std; 不,不,不。
  • 100! 太大,无法容纳 64 位值。
  • 没有可以容纳 100 的内置整数数据类型!您将不得不编写一个类来存储如此大的数字,或者使用其他人的类来完成这项工作。
  • 好吧,我在想如果我用字符串代替整数会怎样。

标签: c++ integer max bit


【解决方案1】:

一个 64 位整数会溢出 23!

因此你需要用数字和向量来做。

这是一个相当简单的任务。我们可以像在一张纸上那样做。我们使用std::vector 的数字来保存号码。因为对于 23 的 unsigned long long,结果已经太大了!。

答案将是准确的。

使用这种方法,计算很简单。我什至不知道该进一步解释什么。

请看代码:

#include <iostream>
#include <vector>

int main()
{
    std::cout << "Calculate n!   Enter n (max 10000): ";
    if (unsigned int input{}; (std::cin >> input) && (input <= 10000)) {

        // Here we store the resulting number as single digits
        std::vector<unsigned int> result(3000, 0);  // Magic number. Is big enough for 100000!
        result.back() = 1;                          // Start calculation with 1 (from right to left)

        // Multiply up to the given input value
        for (unsigned int count = 2; count <= input; count++)
        {
            unsigned int sum{}, remainder{};
            unsigned int i = result.size() - 1;     // Calculate from right to left
            while (i > 0)
            {
                // Simple multiplication like on a piece of paper
                sum = result[i] * count + remainder;
                result[i--] = sum % 10;
                remainder = sum / 10;
            }
        }
        // Show output. Supporess leading zeroes
        bool showZeros{ false };
        for (const unsigned int i : result) {
            if ((i != 0) || showZeros) {
                std::cout << i;
                showZeros = true;
            }
        }
    }
    else std::cerr << "\nError: Wrong input.";
}

使用 bigint 库会快得多。


使用 Microsoft Visual Studio Community 2019 版本 16.8.2 开发和测试。

使用 clang11.0 和 gcc10.2 额外编译和测试

语言:C++17

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 2011-09-27
    • 2015-09-05
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 2020-04-19
    相关资源
    最近更新 更多