用C语言求n!(1<=n<=10000),并统计输出n!中数字“0”的个数和n!中末尾“0”的个数。
时间: 2024-09-23 22:02:46 浏览: 43
在C语言中计算n!(n的阶乘),当n小于等于10000时,可以利用迭代的方式,并结合数学知识来完成。同时,为了找出n!中“0”和末尾“0”的个数,我们需要对每个因数进行分析。
首先,让我们编写一个函数来计算n!:
```c
#include <stdio.h>
unsigned long long factorial(int n) {
unsigned long long fact = 1;
for (int i = 2; i <= n; ++i) {
fact *= i;
}
return fact;
}
```
接下来,我们创建两个辅助函数来统计数字"0"的个数和末尾"0"的个数:
1. 统计总零的个数(所有因数2和5的组合)
```c
int countZerosInFactorial(unsigned long long num) {
int zeros = 0;
while (num > 0) {
zeros += num % 10 == 0;
num /= 10;
}
return zeros;
}
```
2. 统计末尾零的个数(只看因子5)
```c
int countTrailingZerosInFactorial(int n) {
int trailing_zeros = 0;
while (n >= 5) {
n /= 5;
trailing_zeros += n;
}
return trailing_zeros;
}
```
最后,在主函数中调用上述函数:
```c
int main() {
int n;
printf("Enter a number between 1 and 10000: ");
scanf("%d", &n);
if (n < 1 || n > 10000) {
printf("Invalid input. Number should be between 1 and 10000.\n");
return 1;
}
unsigned long long factorial_value = factorial(n);
int total_zeros = countZerosInFactorial(factorial_value);
int trailing_zeros = countTrailingZerosInFactorial(n);
printf("n!: %llu\nTotal '0's: %d\nTrailing '0's: %d\n", factorial_value, total_zeros, trailing_zeros);
return 0;
}
```
阅读全文