Created
March 9, 2019 16:01
-
-
Save computingfreak/113455ae048f2e6ed6200681dd3601fa to your computer and use it in GitHub Desktop.
BigInteger Factorial Dynamic Programming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import java.lang.*; | |
import java.io.*; | |
import java.math.*; | |
class bigintfactorial | |
{ | |
public static Map<BigInteger,BigInteger> nf; | |
public static void main (String[] args) | |
{ | |
Scanner scr=new Scanner(System.in); | |
int n=Integer.parseInt(scr.nextLine()); | |
List numbers=new ArrayList<BigInteger>(); | |
for(int i=0;i<n;i++){ | |
numbers.add(BigInteger.valueOf(Integer.parseInt(scr.nextLine()))); | |
} | |
nf=new HashMap<BigInteger,BigInteger>(); | |
nf.put(BigInteger.ONE,BigInteger.ONE); | |
for(int i=0;i<numbers.size();i++){ | |
System.out.println(fact((BigInteger)numbers.get(i))); | |
} | |
} | |
public static BigInteger fact(BigInteger x){ | |
if(nf.containsKey(x)) { | |
return nf.get(x); | |
} else { | |
return cs(x);//compute and store | |
} | |
} | |
public static BigInteger cs(BigInteger x){ | |
if(nf.containsKey(x.subtract(BigInteger.ONE))) { | |
BigInteger v=nf.get(x.subtract(BigInteger.ONE)).multiply(x); | |
nf.put(x,v); | |
return v; | |
}else { | |
return x.multiply(cs(x.subtract(BigInteger.ONE))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment