牛客网 n的阶乘(大数运算、清华机试)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sunlanchang/article/details/88559622

题目描述

输入一个整数n,输出n的阶乘(每组测试用例可能包含多组数据,请注意处理)

输入描述:

一个整数n(1<=n<=20)

输出描述:

n的阶乘
示例1

输入

3

输出

6

Description

大数运算阶乘板题。

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
string factorial(int n)
{
    int s[100000] = {0}; //数组用来储存结果。
    int sum = 1, i, j, temp = 0, h = 0, l;
    s[0] = 1; //初始化为1。
    l = 1;
    for (i = 2; i <= n; i++) //1就不用在运行了。
    {
        for (j = 1; j <= l; j++) //这里,你想不通就无法理解这个代码。
        {
            temp = s[j - 1] * i + h;
            s[j - 1] = temp % 10;
            h = temp / 10;
        }
        while (h)
        {
            l++;
            s[l - 1] = h % 10;
            h /= 10;
        }
    }
    string res = "";
    for (i = l - 1; i >= 0; i--)
        res += (s[i] + '0');
    return res;
}
int main()
{
    int n;
    while (~scanf("%d", &n))
    {
        string ans = factorial(n);
        printf("%s\n", ans.c_str());
    }
}

猜你喜欢

转载自blog.csdn.net/sunlanchang/article/details/88559622