如何在C ++中找到100的阶乘? [英] How to find the factorial of 100 in C++?

查看:83
本文介绍了如何在C ++中找到100的阶乘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序来计算100的阶乘.代码如下.尽管如此,由于答案太大,输出仍为0.有没有显示确切答案的答案?这是因为即使unsigned long long也不能显示100的阶乘.谢谢.

I am writing a program to calculate the factorial of 100. The code is as below. Notwithstanding, the output is 0 as the answer is too big. Is there any answer to display the exact answer? This is because even unsigned long long is not even able to display the factorial of 100. Thank you.

#include <iostream> 
using namespace std; 
int main() 
{
    int n,i,fact=1; 
    cout << "enter the number "<<endl; 
    cin>>n; 
    for(i=1;i<=n;i++) 
    { 
       fact=fact*i; 
    } 
    cout<<"the factorial is "<<fact<<endl; 
} 

推荐答案

这是一个非常简单的任务.我们可以像在纸上一样完成它.我们使用数字的 std :: vector 来保存数字.因为结果对于22的 unsigned long long 来说已经太大了.

This is a rather simple task. We can do it like we would do it on a piece of paper. We use a std::vector of digits to hold the number. Because the result will be already too big for an unsigned long long for 22!.

答案将是准确的.

采用这种方法,计算很简单.我什至不知道该怎么解释.

With such an approach the calculation is simple. I do not even know what to explain further.

请查看代码:

#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.";
}


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


Developed and tested with Microsoft Visual Studio Community 2019, Version 16.8.2.

另外使用clang11.0和gcc10.2进行了编译和测试

Additionally compiled and tested with clang11.0 and gcc10.2

语言:C ++ 17

Language: C++17

这篇关于如何在C ++中找到100的阶乘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆