CSU - 1594 Factorials

来源:互联网 发布:linux循环新建文件命令 编辑:程序博客网 时间:2024/06/05 15:34

题目:

Description

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.

Input

This problem includes multiple cases. The first line of input is a integer T represents the number of cases. 
For each case, there is a single positive integer N no larger than 4,220.

Output

For each case, output corresponding results separately.
The output of each case is a single line containing but a single digit: the right most non-zero digit of N!.

Sample Input

17

Sample Output

4

有个题目是这个题目的直接推广,我先做了那个题目,所以这个题目秒了。

点击打开链接(SCU - 1115 阶乘)

代码:

#include<iostream>using namespace std;int degree_in_fact(int m, int p){if (m)return degree_in_fact(m / p, p) + m / p;return 0;}int main(){int k, n;cin >> k;while (k--){cin >> n;int num = degree_in_fact(n, 5);int fact = 1;for (int i = 1; i <= n; i++){int j = i;while (j % 2 == 0 && num){j /= 2;num--;}while (j % 5 == 0)j /= 5;fact = fact*j % 10;};cout << fact << endl;}return 0;}

1 0
原创粉丝点击