2014-04-28 22:18

题目:计算N的阶乘尾巴上有多少个零?

解法:计算5的个数即可,因为2 * 5 = 10,2的个数肯定比5多。计算5的个数可以在对数时间内搞定。

代码:

 1 // 17.3 Count how many zeros are there in n!?
 2 // Count the number of 5s in n!.
 3 #include <cstdio>
 4 using namespace std;
 5 
 6 int countZero(int n)
 7 {
 8     int res = 0;
 9     
10     while (n > 0) {
11         res += n / 5;
12         n /= 5;
13     }
14     
15     return res;
16 }
17 
18 int main()
19 {
20     int n;
21     
22     
23     while (scanf("%d", &n) == 1) {
24         printf("%d\n", countZero(n));
25     }
26     
27     return 0;
28 }

 

相关文章:

  • 2022-01-29
  • 2021-10-25
  • 2021-10-30
  • 2021-11-28
  • 2021-09-13
  • 2022-02-18
  • 2021-06-16
  • 2021-09-12
猜你喜欢
  • 2022-01-24
  • 2021-11-04
  • 2021-08-12
  • 2021-09-19
  • 2021-12-30
  • 2021-06-25
  • 2021-10-03
相关资源
相似解决方案