首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

1024!末尾有几个零?解决方法

2012-03-12 
1024!末尾有几个零?1024!末尾有几个零?[解决办法]C/C++ code#include stdio.hint totalzero(int n){int

1024!末尾有几个零?
1024!末尾有几个零?

[解决办法]

C/C++ code
#include <stdio.h>int totalzero(int n){    int total = 0;    while (n > 5)    {        n = (n - (n % 5)) / 5;        total += n;    }    return total;}void main(){    printf("%d\n", totalzero(1024));}
[解决办法]
两个办法:
1. 暴力做法:用大数计算1024!,然后再看后面有多少个0。大数计算的代码可以参考:
大数的四则运算及求模

2. 巧慧做法:看1到1024这些数中,有多少个个位是0和5的数字,比如
10! = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10
因为5和其前面的任何一个偶数相乘都会产生0,个位本身是0的情况就更不用说了。所以10!最后有2个0.

由此可以推知15!最后有3个0...

当然特殊的情况需要注意,比如数字是100,1000这样的情况,还有50,500这样的情况,楼主稍加思考不难得出正确的结论。
[解决办法]
Python code
m=input("Calculate N!, input N:")n, r = 1, 1while n <= m:    r=r*n    n=n+1print r
[解决办法]
http://book.51cto.com/art/200909/150056.htm
上面的链接很适合楼主……
或者,楼主google一下“不要被阶乘吓到”
[解决办法]
赵哥v5……
公式:1024/5+1024/25+1024/125+1024/625
=204 + 40 + 8 + 1 =253
[解决办法]
记得小学数学奥林匹克题目是这样的,
答案确实是253
算法简单:10 = 2 *5,必须有5的因子才可能乘到10;
所以计算1到1024中分解出5因子个数即得到结果。
[解决办法]
There is a formula for finding the number of zeros a factorial number will have. 
It is: 

floor(n/5) + floor(n/25) + floor(n/125) + ... + floor(n/5^n) + ... 

The floor function means round down to the nearest integer. 

For example, let's take 5!, or n = 5. 

floor(5/5) = floor(1) = 1. 

So, 5! ends in 1 zero. 

Let's go to 15! 

floor(15/5) = floor(3) = 3 

So, 15! ends in 3 zeros. 

Let's move on to 100!. 

floor(100/5) + floor(100/25) = floor(20) + floor(4) = 20 + 4 = 24

If you went to 200, you would have to use the next power of 5, or 5^3 = 125. 




The reason this works is that a number ends in 0 if it is divisible by 10. Divisible by 10 means divisible by both 5 and 2. But there are lots of numbers divisible by 2 (half of them). So, we concentrate on the number of times a number is divisible by 5. But there are tricky numbers like 25, which are divisible by 5 twice, so we have to take those into account (or floor(n/25)). Then again, there are numbers that are divisible by 5 three times, like 125, so we have to take them into account.

热点排行