Pages

Thursday 27 September 2012

UVA - 568 - Just the Facts

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;

public class Main {

    public static void main(String[] args) throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        StringBuffer sb = new StringBuffer("");
        String m = "";
        BigInteger[] fact=new BigInteger[10002];
         for (int i = 0; i < 10002; i++) {
            fact[i]=BigInteger.ZERO;
        }
        
        for (int i = 0; i < 10002; i++) {
           fact(i,fact);
        }
        int xl=2;
       while((m=br.readLine())!=null) {
            int x=Integer.parseInt(m);
            String temp1=x+"";
            for(int i=temp1.length();i<5;i++){
                sb.append(' ');
            }
            String temp=fact[x].toString();
            char rem='0';
            for(int i=temp.length()-1;i>-1;i--){
                if(temp.charAt(i)!='0'){
                    rem=temp.charAt(i);
                    break;
                }
            }
            sb.append(temp1).append(" -> ").append(rem).append("\n");
        }
        System.out.print(sb);
    }

    static BigInteger fact(int x,  BigInteger[]arr) {
        if (x == 0) {
            return BigInteger.ONE;
        }
        if(arr[x].compareTo(BigInteger.ONE) == 1){
            return arr[x];
        }
        else{
            arr[x]=BigInteger.valueOf(x).multiply(fact(x-1, arr));
        }
        return arr[x];
    }
}

No comments:

Post a Comment