N! Plus

题目描述

Given an integer N(0 ≤ N ≤ 10000), your task is to calculate N!.

解答要求
时间限制:5000ms, 内存限制:100MB
输入
One N in one line.

输出
For each N, output N! in one line.

样例
输入样例 1
3
输出样例 1
6

直接计算

// we have defined the necessary header files here for this problem.
 // If additional header files are needed in your program, please import here.
int main()
{
// please define the C input here. For example: int n; scanf("%d",&n);
// please finish the function body here. 
// please define the C output here. For example: printf("%d\n",a);    
double n,sum;
scanf("%lf",&n);
sum=n;
for(int i=n;i>=2;i--){
    sum=sum*(i-1);
}

printf("%.0lf",sum);

return 0;
}

这样计算会超过范围,因此我们还是应该使用大数相乘的方法

大数相乘

void array_MUL(char *a, char* b)
{
int m = strlen(a);
int n = strlen(b);
char c[m + n];
//特殊case处理:乘数为0
if (a[0] == '0' || b[0] == '0') {  
    printf("0\n");
    return;
}
memset(c, 0, m + n);
//printf("m=%d,n=%d\n", m, n);
for (int i = m - 1; i >= 0; i--) {
    for (int j = n - 1; j >= 0 ; j--) {
        c[i + j + 1] += (a[i] - '0') * (b[j] - '0');
        c[i + j] += c[i + j + 1] / 10;
        c[i+ j + 1] = c[i + j + 1] % 10;
    }
}
if (c[0] != 0) {
    printf("%c", c[0]+'0');
}
for (int i = 1; i < m + n; i++) {
    printf("%c", c[i]+'0');
}
printf("\n"); 
}
posted @ 2022-02-08 15:56  ly-828  阅读(93)  评论(0)    收藏  举报