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
-K Himaanshu Shuklaa..
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
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
//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); | |
} | |
} |
-K Himaanshu Shuklaa..
No comments:
Post a Comment