考研机试真题--N的阶乘--清华大学

关键字:大整数乘法(大精度*小精度)

题目:
题目描述
输入一个正整数N,输出N的阶乘。
输入描述:
正整数N(0<=N<=1000)
输出描述:
输入可能包括多组数据,对于每一组输入数据,输出N的阶乘
示例1
输入
4
5
15
输出
24
120
1307674368000

链接:
https://www.nowcoder.com/practice/f54d8e6de61e4efb8cce3eebfd0e0daa?tpId=40&tqId=21355&tPage=1&rp=1&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

代码:

#include <iostream>
#include <fstream>
using namespace std;
const int maxn = 10010;

int main(){
    //    freopen("a.txt", "r", stdin);
    int n;
    while(cin >> n){
        int ans = 1, t = 0, tmp, carry, i, j;
        int d[maxn] = {0};
        d[0] = 1;
        for(i = 1; i <= n; ++i){
            carry = 0;
            for(j = 0; j <= t; ++j){
                tmp = (d[j] * i + carry) / 10;
                d[j] = (d[j] * i + carry) % 10;
                carry = tmp;
            }
            while(carry > 0){
                d[++t] = carry % 10;
                carry /= 10;
            }
        }
        for(i = t; i >= 0; --i){
            cout << d[i];
        }
        cout << endl;
    }
}

猜你喜欢

转载自blog.csdn.net/Void_worker/article/details/81463229