2013
11-10

# 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 <= N <= 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 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!.

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!.

1
2
26
125
3125
9999

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

//* @author: 82638882@163.com
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int[] b2=new int[]{6,2,4,8};
int[] b3=new int[]{1,3,9,7};
int[] b7=new int[]{1,7,9,3};
int[] b9=new int[]{1,9,1,9};
while(in.hasNext())
{
int n=in.nextInt();
int e,a2=0,a3=0,a5=0,a7=0,a9=0;
e=n;while((e=e/2)!=0) a2+=e;
e=n;while((e=e/5)!=0) a5+=e;
a3=f(n,3);
a7=f(n,7);
a9=f(n,9);
int ans=1;
a2-=a5;
if(a2!=0){
a2=a2%4;
ans*=b2[a2];
}
ans*=b3[a3%4];
ans=ans%10;
ans*=b7[a7%4];
ans=ans%10;
ans*=b9[a9%4];
ans=ans%10;
System.out.printf("%5d",n);
System.out.println(" -> "+ans);
}
}

public static int f(int n,int a)
{
if(n==0) return 0;
else return f(n/2,a)+g(n,a);
}
public static int g(int n,int a)
{
if(n==0) return 0;
else if(n%10< a) return n/10+g(n/5,a);
else return n/10+1+g(n/5,a);
}
}

1. 可以参考算法导论中的时间戳。就是结束访问时间，最后结束的顶点肯定是入度为0的顶点，因为DFS要回溯