Pages

July 28, 2019

Factorial using recursion in Java

Write a program to calculate Factorial of a number using recursive function. To improve the performance, try to use HashMap, which will store the calculated factorials that can be reused.

FYI, Factorial of n is the product of all positive descending integers. Factorial of n is denoted by n!.

e.g:
3!=3*2*1=6
4!=4*3*2*1=24
5!=5*4*3*2*1=120

//factorial using loop
public void factorial(int n){
int i,fact=1;
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of "+n+" is: "+fact);
}
//factorial using recursion
int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
//factorial using HashMap for caching
public static void factorialRecursively(int input) {
Map<Integer, Integer> cache = new HashMap<Integer, Integer>();
cache.put(1, 1);
if (cache.get(input) != null) {
System.out.println("Factorial found in cache."
+input + "! = " + cache.get(input));
} else {
int result = factorialRecursively(input, cache);
System.out.println(input + "! = " + result);
}
}
public static int factorialRecursively(int input,
Map<Integer, Integer> cache) {
int cacheSize = cache.size();
if (cacheSize < input) {
int nextFactorial = cacheSize + 1;
System.out.println("Calculating and caching " + nextFactorial + "!");
cache.put(nextFactorial, cache.get(cacheSize) * nextFactorial);
return factorialRecursively(input, cache);
} else {
return cache.get(input);
}
}
view raw Factorial.java hosted with ❤ by GitHub


-K Himaanshu Shuklaa..

No comments:

Post a Comment