The problem of recursion arises when calculations are already calculated previously, the recursion calculates and repeats calculations until reaching the base case.
I'd better explain it with an image, the factorial (3) and the factorial (4) with recursion:
According to the image, to obtain the factorial(3)
the factorial(2)
and factorial(1)
is calculated, then to obtain the factorial(4)
it also calculates the factorial(2)
and factorial(1)
, then the recursion repeats calculations, that is very bad for execution times .
Why not save the results and use them when you need it? That way they will not be calculated again and again, you only calculate once and that's it.
The code I expose only calculates once and saves them,
for when I need it, that way I do not calculate again and again
time.
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
System.out.println(factorial(100));
}
public static double factorial(int n) {
double result[]=new double [1000] ;
result[0] = 1;
for (int i = 1; i <= n; ++i) {
result[i] = i * result[i - 1];
}
return result[n];
}
}
according to comments, good observations !!!:
Iterative or recursive the problem that you mention would be given of all
forms and that certainly does not apply in this case. Useless
store the intermediate results if then they are going to discard all
except the last one
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
double result[]=new double [1000] ;
public Main(){
result[0] = 1;
}
public static void main(String[] args) {
System.out.println(factorial(100));
}
public static double factorial(int n) {
if(!result[n]){
for (int i = 1; i <= n; ++i) {
result[i] = i * result[i - 1];
}
return result[n];
}else{
return result[n];
}
}
}