USACO 3.2 Factorials


这题主要是去掉阶乘末尾的0。是个老题了,编程之美中就有讨论。因为0都是由2*5得来的。只要找出乘数中有多少个2*5对就行了。
因为2的个数远多于5,所以只要找出5的个数即可。因为n最大为4220,5的个数为:
n/5+n/5/5+n/5/5/5+n/5/5/5/5+n/5/5/5/5/5+n/5/5/5/5/5/5;
然后再去除相应数目的2。这样剩下的数只需两两相乘后取最后一位即可。

#include <iostream>
#include 
<fstream>

using namespace std;

ifstream in(
"fact4.in");
ofstream out(
"fact4.out");

void solve()
{
    
int n;
    
in>>n;

    
int numof5 = n/5+n/5/5+n/5/5/5+n/5/5/5/5+n/5/5/5/5/5+n/5/5/5/5/5/5;

    
int res = 1;

    
int tmp;

    
for(int i=1;i<=n;++i){
        tmp 
= i;
        
while(tmp%5==0) tmp/=5;
        
while(tmp%2==0&&numof5!=0){
            tmp
/=2;
            numof5
--;
        }
        res
*=tmp;
        res
%=10;
    }

    
out<<res<<endl;
}

int main(int argc,char *argv[])
{
    solve(); 
    
return 0;
}


原题:
Factorials

The factorial of an integer N, written N!, is the product of all the integers from 1 through N inclusive. The factorial quickly becomes very large: 13! is too large to store in a 32-bit integer on most computers, and 70! is too large for most floating-point variables. Your task is to find the rightmost non-zero digit of n!. For example, 5! = 1 * 2 * 3 * 4 * 5 = 120, so the rightmost non-zero digit of 5! is 2. Likewise, 7! = 1 * 2 * 3 * 4 * 5 * 6 * 7 = 5040, so the rightmost non-zero digit of 7! is 4.

PROGRAM NAME: fact4

INPUT FORMAT

A single positive integer N no larger than 4,220.

SAMPLE INPUT (file fact4.in)

7

OUTPUT FORMAT

A single line containing but a single digit: the right most non-zero digit of N! .

SAMPLE OUTPUT (file fact4.out)

4

posted on 2009-07-03 19:52 YZY 阅读(230) 评论(0)  编辑 收藏 引用 所属分类: AlgorithmUSACO


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2009年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

统计

常用链接

留言簿(2)

随笔分类

随笔档案

搜索

积分与排名

最新评论

阅读排行榜