Fork me on GitHub

Uva 568 - Just the Facts

  Just the Facts 

The expression N!, read as ``N factorial," denotes the product of the first N positive integers, where N is nonnegative. So, for example,

 

N N!
0 1
1 1
2 2
3 6
4 24
5 120
10 3628800

For this problem, you are to write a program that can compute the last non-zero digit of any factorial for ($0 \le N \le 10000$). For example, if your program is asked to compute the last nonzero digit of 5!, your program should produce ``2" because 5! = 120, and 2 is the last nonzero digit of 120.

 

Input 

Input to the program is a series of nonnegative integers not exceeding 10000, each on its own line with no other letters, digits or spaces. For each integer N, you should read the value and compute the last nonzero digit of N!.

 

Output 

For each integer input, the program should print exactly one line of output. Each line of output should contain the value N, right-justified in columns 1 through 5 with leading blanks, not leading zeroes. Columns 6 - 9 must contain `` -> " (space hyphen greater space). Column 10 must contain the single last non-zero digit of N!.

 

Sample Input 

1
2
26
125
3125
9999

 

Sample Output 

    1 -> 1
    2 -> 2
   26 -> 4
  125 -> 8
 3125 -> 2
 9999 -> 8

 

 


Miguel A. Revilla 
1998-03-10
 
#include<stdio.h>

int main()
{

    long long i, n, m, temp;
    while(scanf("%lld", &n) != EOF)
    {
        for(m=i=1; i<=n; ++i)
        {
            temp = i;
            while(temp%10 == 0) temp /= 10;
            m *= temp;
            while(m%10 == 0) m /= 10;
            m = m%100000;
        }
        printf("%5lld -> %lld\n", n, m%10);
    }
    return 0;
}

解题思路:

题目意思是说要你求n(n<=10000)的阶乘最后一位不为零的数字,

解决的方法主要是用求模保存在范围内的数,因为n<=10000,存储不了那么大的数,而每次要保存的数并不能仅仅是最后一位,因为可能跟下一个相乘后此时会成为零,同时为了保证不溢出,也要对第二个因子取整

差点WA了,还在测试数据还过得去,用int导致了中间的值溢出,导致最后求的不为零尾数改变,算是一题简单题了。

posted @ 2013-03-08 20:11  Gifur  阅读(686)  评论(0编辑  收藏  举报
TOP