I am finding the factorial and exponents of variables both recursively and iteratively. What I need help with is finding out how long it took each one. Where do I put the System.currentTimeMillis() part and how do I find out exactly how long it took (i.e. 55 milliseconds)?
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("What integer do you want to get the factorial of?");
int n = scan.nextInt();
System.out.println("The Recursive factorial of " + n + " is " + recur(n) + ".");
System.out.println("The Iterative factorial of " + n + " is " + iter(n) + ".");
System.out.println("What two integers do you want to get the exponent of? (a to the x)");
int a = scan.nextInt();
int x = scan.nextInt();
System.out.println("The Recursive exponent of " + a + " is " + recurs(a, x) + ".");
System.out.println("The Iterative exponent of " + a + " is " + itera(a, x) + ".");
}
public static int recur(int n){
if(n == 0){
return 1;
}
else
return n * recur(n-1);
}
public static int iter(int n){
if (n <= 1) {
return 1;
}
int it = n;
for (int i = n - 1; i > 1; --i) {
it *= i;
}
return it;
}
public static int recurs(int a, int x){
if (x == 0)
return 1;
else if (x == 1)
return a;
else
return a * recurs(a, x-1);
}
public static int itera(int a, int x){
int r = a;
if (x == 0)
return 1;
else if (x == 1)
return a;
else
for (int i = 1; i <= x; i ++){
r *= a;
}
return r;
}