HDU - 1024 N!

写过了高精度的加法,这次是高精度的阶乘

关于数目过大的计算就要利用数组来做,只要注意进位,然后取余(和加法类似)。没什么多大的弯,不过注意的是要先进位在取余,二者不可调换位置
至于原因很容易想明白

至于减法丶除法。以后日子遇到题里慢慢了解吧…
在这里插入图片描述
代码很简单的

#include <iostream>
#include <cstring>
using namespace std;
int a[1000000], n;
int main()
{
    while(cin >> n)
    {
        memset(a, 0, sizeof(a));
        a[0] = 1; // 这里的0表示个位
        int pos = 1; // pos 表示初始一共有一位
        for(int i = 2; i <= n; ++i)
        {
            for(int j = 0; j < pos; ++j)
                a[j] *=  i;
            for(int j = 0; j < pos; ++j)
            if(a[j] >= 10){
                a[j+1] += a[j]/10;
                a[j] %= 10;
                if(j == pos-1) pos++; // 如果 i == pos - 1 表示进位
            }
        }
        for(int i = pos-1; i >= 0; --i)
            cout << a[i];
        cout << endl;
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/weixin_44031744/article/details/88084985