网上看到的这个算法,我在中间注释了不懂的地方,求大神梳理思路
#include <stdio.h>
#include <string.h>
int main()
{
int a[3000];//用来存储阶乘后的数
int n,i,j;
int c = 0;//起初将进位设置为0
int s;//每个位上的数
scanf("%d",&n);
//先将数组a所有的空间都初始化为0
memset(a,0,sizeof(a));
a[0] = 1;//1的阶乘
//计算阶乘
//*********这一段计算阶乘不懂啊***********
for(i = 2; i <= n; i++)
{
for(j = 0; j < 3000; j++)
{
s = a[j] * i + c;
a[j] = s % 10;
c = s / 10;
}
}
//去掉前面为0的
for(i = 3000 - 1; i >= 0; i--)
{
if(a[i] != 0)
break;
}
for(j = i; j >= 0; j--)
{
printf("%d",a[j]);
}
}
s = a[j] * i + c
表示a[j]位乘以阶乘的下一个数,然后加上j-1位的进位值c
a[j] = s % 10
取结果的个位数作为新的第j位的值
c = s / 10
取结果的第二位以上部分作为第j位的进位值,如此往复
例如 a=1234 * i=25
s = 4 * 25 + 0 = 100; a[0] = 100%10 = 0; c = 100/10 = 10;
此时a = 1230,c = 10
s = 3 * 25 + 10 = 85; a[0] = 85 %10 = 5; c = 85 /10 = 8;
此时a = 1250,c = 8
s = 2 * 25 + 8 = 58; a[0] = 58 %10 = 8; c = 58 /10 = 5;
此时a = 1850,c = 5
s = 1 * 25 + 5 = 30; a[0] = 30 %10 = 0; c = 85 /10 = 3;
此时a = 0850,c = 3
s = 0 * 25 + 3 = 3; a[0] = 3 %10 = 3; c = 3 /10 = 0;
此时a = 30850,c = 0
赶巧了我也刚刷到高精度的题,我的高精度都不是一位一位做的