Skip to content

Instantly share code, notes, and snippets.

@computingfreak
Created March 9, 2019 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save computingfreak/113455ae048f2e6ed6200681dd3601fa to your computer and use it in GitHub Desktop.
Save computingfreak/113455ae048f2e6ed6200681dd3601fa to your computer and use it in GitHub Desktop.
BigInteger Factorial Dynamic Programming
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