标签:des style blog http color os io ar strong
| Time Limit: 1500MS | Memory Limit: 65536K | |
| Total Submissions: 13993 | Accepted: 8678 |
Description
Input
Output
Sample Input
6 3 60 100 1024 23456 8735373
Sample Output
0 14 24 253 5861 2183837
题目:http://poj.org/problem?id=1401
题目是求N!中末尾0的个数。
这道题,是我曾经在经典例题100道中看到的,做出来的,可是,发现理解错了。(感谢一位网友的提醒啊!)
所以,又一次做一下,发现poj上有这道题,正好能够拿来測试一下做的是否正确。
这道题做法,显然不能求出来阶乘再数0的个数。
所以,要换一个思路。
为什么会产生0呢?源于2x5,于是能够通过数有多少个(2,5)因子对来推断有多少个0.
我们又能够发现,5的个数永远会大于2的个数。
又能够简化为数5的个数来做。
当时,还非常年轻,做法让如今的我看,有点纠结啊。。
当时做的是,从1到N(所输入的数)循环,看看能不能被5整除,若能整除,继续除5,直到不能整除为止。
这个做法显然答案正确,可是在这道题里,TLE必须的。。。
#include <stdio.h>
int main()
{
int i,N,k,t;
double num;
bool prime;
scanf("%d",&t);
while( t-- )
{
scanf("%d",&N);
k=0;
for(i=1;i<=N;i++) //查看有多少个5
{
num=i/5.0;
if(num-int(num)==0)
prime=true;
else
prime=false;
while(num>=1&&prime==true)
{
num/=5.0;
if(num-int(num)==0)
prime=true;
else
prime=false;
k+=1;
}
}
printf("%d\n",k);
}
return 0;
}
数5的倍数,就能够了。
以698为例:
698/5=139.6→取整→139 (表示有139个数为5的倍数) sum=sum+139 (sum初始化为0)
139/5=27.8 →取整→27 (表示有27个数为25的倍数)sum=sum+27
(为什么25的倍数,仅仅加了一遍,不应该加 27*2的吗,25表示两个5?
由于,25的之前有一个5,在第一遍139个里面算过一次了,所以不须要加两遍。)
27/5=5.4 → 取整→5 (表示有5个数为125的倍数)sum=sum+5
5/5=1 → 取整 → 1 (表示有1个数为625的倍数) sum=sum+1
1/5=0 结束。
所以答案是 139+27+5+1=172
恩,所以程序,就非常easy了:
/**************************************
***************************************
* Author:Tree *
*From :http://blog.csdn.net/lttree *
* Title : Factorial *
*Source: poj 1401 *
* Hint : N!求0的个数 *
***************************************
**************************************/
// scanf 125MS, cin 422MS
#include <stdio.h>
int main()
{
// sum为答案,存储每次除5后的数(累加)
int t,n,sum;
scanf("%d",&t);
while( t-- )
{
sum=0;
scanf("%d",&n);
while( n )
{
n/=5;
sum+=n;
}
printf("%d\n",sum);
}
return 0;
}
标签:des style blog http color os io ar strong
原文地址:http://www.cnblogs.com/hrhguanli/p/3960315.html