题解 | #N的阶乘#
N的阶乘
https://www.nowcoder.com/practice/f54d8e6de61e4efb8cce3eebfd0e0daa
//推荐博客https://www.cnblogs.com/wuqianling/p/5387099.html,讲的很好 //字符串大数乘法,加法有些笛卡尔积的思想 #include "stdio.h" #include "string" #define MAX 4010 using namespace std; int MulString(char sum[],string buf2){ string buf1 = sum; int num1[MAX];int num2[MAX];int num3[MAX*2]={0}; int len1 = buf1.size(); int len2 = buf2.size(); for (int i = len1-1, j = 0; i >= 0; --i) { num1[j++] = buf1[i] - '0'; } for (int i = len2-1,j = 0; i >= 0; --i) { num2[j++] = buf2[i] - '0'; } for (int i = 0; i < len1; ++i) { for (int j = 0; j < len2; ++j) { num3[i+j] = num3[i+j]+num1[i]*num2[j]; } } for (int i = 0; i < len1+len2+1; ++i) {//依次进位 if (num3[i] > 9){ num3[i+1] = num3[i+1] + num3[i]/10; num3[i] = num3[i] % 10; } } int len3; for (len3 = MAX*2-1; num3[len3] == 0 && len3 >= 0 ; --len3); ++len3; for (int i = 0; i < len3; ++i) { sum[len3-i-1] = num3[i] + '0'; } return len3; } int main(){ int N; while (scanf("%d",&N)!=EOF){ char sum[MAX*2]={}; sum[0] = '1'; int len; for (int i = 2; i <= N; ++i) { len = MulString(sum,to_string(i)); } for (int i = 0; i < len ; ++i) { printf("%c",sum[i]); sum[i] = '0'; } printf("\n"); } }