Advertisement
Guest User

Untitled

a guest
May 12th, 2017
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.55 KB | None | 0 0
  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import java.math.BigInteger;
  4. import java.util.ArrayList;
  5. import java.util.Collections;
  6. import java.util.List;
  7. import java.util.Scanner;
  8.  
  9. public class Main {
  10.    
  11.     public static BigInteger[] compute(int max){
  12.         BigInteger[] nFact = new BigInteger[max];
  13.         //First value is 1! = 1.
  14.         nFact[0] = new BigInteger("1");
  15.         for (int i = 1; i < max; i++) {
  16.             nFact[i] = nFact[i-1].multiply(new BigInteger(i+1+""));
  17.         }
  18.         return nFact;
  19.     }
  20.    
  21.     public static void main(String[] args) throws IOException {
  22.         //Initiazing I/O
  23.         Scanner sc = new Scanner(System.in);
  24.         PrintWriter stdout = new PrintWriter(System.out);
  25.         //Getting number of inputs
  26.         int n = sc.nextInt();
  27.         List<Integer> values = new ArrayList<Integer>();
  28.         //Store all the inputs in the list "values"
  29.         for (int i = 0; i < n; i++) values.add(sc.nextInt());
  30.         //Get the largest input using the max method from the Collections class.
  31.         int max = Collections.max(values);
  32.         //Call the compute method to get max! and store all steps in an array.
  33.         BigInteger[] nFact = compute(max);
  34.         //At that point we should have an array of that for; [1!, 2!, 3!, ..., (max-1)!, max!]
  35.         //For example if we assume max = 100, and we want to get 74!, we should just access the array at the position (74-1)=73.
  36.         for (int i = 0; i < n; i++) {
  37.             //For each input, we retrieve its value from the list "values" and then get its factorial from the "nFact" array.
  38.             stdout.println(nFact[values.get(i)-1]);
  39.         }
  40.         sc.close();
  41.         stdout.flush();
  42.         stdout.close();
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement