n的阶乘 C++

描述

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

4
5
15

输出

24
120
1307674368000

分析

在n<20的范围内还能考虑用long long表示,这个范围肯定要用数组了
值得注意的是未必要用字符串来表示,用整数数组每次一位也可以,而且倒序输出就好了,不一定按照正常的顺序

代码

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxx = 5000;
int str[maxx];
void Cal(int n)
{
    for (int i = 0; i<maxx; i++)str[i] = 0;
    str[1] = 1; int j;
    int len = 1, c = 0;
    for (int i = 2; i <= n; i++)
    {
        for (j = 1; j <= len; j++)
        {
            str[j] = str[j] * i + c;
            c = str[j] / 10;
            str[j] = str[j] % 10;

        }
        while (c>0)
        {
            str[j] = c % 10;
            j++;
            c /= 10;
        }
        len = j - 1;
    }
    for (int j = len; j >= 1; j--)
        cout << str[j];
    cout << "\n";
}
int main()
{
    int n;
    while (cin >> n)
    {
        if (n == 0)printf("1\n");
        else Cal(n);

    }
}

猜你喜欢

转载自blog.csdn.net/BeforeEasy/article/details/81530852