测评会员优惠活动进行中 · 开通 VIP,有效期内测评不限次 VIP 优惠中 · 测评不限次 立即查看

A24193. 求10000以内n的阶乘

填空题 困难

题目描述

求10000以内n的阶乘

题目描述

求10000以内n的阶乘。

输入

只有一行输入,整数n(0≤n≤10000)。

输出

一行,即n!的值。

输入样例

4

输出样例

24

参考答案

#include <bits/stdc++.h> using namespace std; #define N 40005 void setLen(int a[], int i) { while(a[i] == 0 && i > 1)//去除多余的0 i--; a[0] = i; } void Multiply(int a[], int b)//a *= b 高精乘低精 { int c = 0, i; for(i = 1; i <= a[0]; ++i) { a[i] = a[i]*b + c; c = a[i] / 10; a[i] %= 10; } while(c > 0) { a[i] = c % 10; c /= 10; i++; } setLen(a, i); } void toNum(char s[], int a[]) { a[0] = strlen(s); for(int i = 1; i <= a[0]; ++i) a[i] = s[a[0] - i] - '0'; } void showNum(int a[]) { for(int i = a[0];i >= 1;--i) cout << a[i]; } int main() { int a[N] = {1, 1}, n;//高精度数字a初值为1 cin >> n; for(int i = 1; i <= n; ++i) Multiply(a, i); showNum(a); return 0; }

答案解析

#include <bits/stdc++.h>

using namespace std;

int main() {

   int n;

   cin>>n;

   vector<int> r(1,1);

   if(n==0) cout<<1;

   for(int i=1;i<=n;i++){

    int c=0;

    for(int j=0;j<r.size();j++){

    int t=r[j]*i+c;

    r[j]=t%10;

    c=t/10;

}

while(c){

r.push_back(c%10);

c/=10;

}

}

for(int i=r.size()-1;i>=0;i--){

cout<<r[i];

}

   return 0;

}

上一题 下一题