标签:n的阶乘 void numa == add 最大 amp can oid
题目描述:
输入N(0<=N<=1000),输出N的阶乘。
开始使用大数加法完成,当然超时了:
#include <cstdio> #include <math.h> #include <cstring> #include <algorithm> int res[1001][1000] = {0}; int num[1001]; //大数加法 Num + Res = res // 计算 res[a] + res[a+1] = rea[a+1] void BigNumAdd(int a) { int k=0; for(int i=0; i<num[a]; i++){ int temp = res[a][i] + res[a+1][i]; if(temp >= 10){ res[a+1][i] = temp%10; int k = i+1; while(true){ if(res[a+1][k] == 9)res[a+1][k] = 0; else{ res[a+1][k] += 1; break; } k++; } //res最高位进位 if(k >= num[a+1]){ num[a+1] = k+1; } } else{ res[a+1][i] = temp; } } } void caculate(int nowN, int N) { for(int i=nowN+1; i<=N; i++){ num[i] = num[i-1]; for(int j=1; j<=i; j++){ BigNumAdd(i-1); } } } int main() { res[0][0] = 0; res[1][0] = 1; res[2][0] = 2; num[0] = 1; num[1] = 1; num[2] = 1; int N; //目前计算到的最大整数 int maxN = 2; while(~scanf("%d",&N)){ if(N <= maxN){ for(int i=num[N]-1; i>=0; i--){ printf("%d",res[N][i]); } printf("\n"); continue; } caculate(maxN, N); for(int i=num[N]-1; i>=0; i--){ printf("%d",res[N][i]); } printf("\n"); maxN = N; } return 0; }
然后使用乘法来做,具体思路:把结果存于数组中,计算n+1的阶乘时,将res(n)数组中的每一位乘n+1,然后继续存储在数组中。
#include <cstdio> #include <math.h> #include <cstring> #include <algorithm> //存储结果 int a[20001]; int main() { int n; //tNum 结果的位数 int tNum; while(~scanf("%d",&n)){ a[0]=1; tNum=1; //开始阶乘 for(int i=2; i<=n; i++) { int num = 0; //将每一位都乘i for(int j=0; j<tNum; j++) { int temp = a[j] * i + num; a[j] = temp % 10; num = temp / 10; } //循环将num剩下的值 while(num) { a[tNum] = num % 10; num = num / 10; tNum++; } } //倒序输出 for(int i=tNum-1; i>=0; i--) printf("%d",a[i]); printf("\n"); } return 0; }
标签:n的阶乘 void numa == add 最大 amp can oid
原文地址:https://www.cnblogs.com/farewell-farewell/p/9123957.html