I am comparing the time to compute both iterative and recursive factorial procedures in Java. I am trying to use the System.currentTimeMillis
method to compare the time it takes for each algorithm to compute, but I can't seem to calculate the difference. I am not sure what the proper way to use this method is, but any event here is what I am trying to achieve in my code:
// ... more code above
System.out.print("Please enter an integer: ");
int integer = readInt();
System.out.println();
// demonstrate recursive factorial and calculate
// how long it took to complete the algorithm
long time1 = System.currentTimeMillis();
int fact1 = factRecursive(integer);
long time2 = System.currentTimeMillis();
System.out.format("Result of recursive factorial %s is %d\n", integer, fact1);
System.out.format("Algorithm took %d milliseconds\n\n", (time2 - time1));
// ... more code below
Here is the output:
Please enter an integer: 25
Result of recursive factorial 25 is 2076180480
Algorithm took 0 milliseconds
Result of iterative factorial 25 is 2076180480
Algorithm took 0 milliseconds
Clearly I must be doing something wrong here, as the amount of time expected to compute factorials for both cases shouldn't be zero.
EDIT: Here are my solutions for factorial, if anyone is interested (not particularly unique, but here they are anyway):
// factRecursive uses a recursive algorithm for
// caluclating factorials.
public static long factRecursive(long n)
{
return n = (n == 1)? 1 : n * factRecursive(n - 1);
}
// factIterative uses an iterative algorithm for
// calculating factorials.
public static long factIterative(long n)
{
long product = 1;
if(n == 1) return n;
for(int i = 1; i <= n; ++i)
product *= i;
return product;
}
And is some output. Surprisingly, the recursive version holds up well. It isn't until about 39! that the iterative version starts performing noticeably better.
Please enter an integer: 39
Result of recursive factorial 39 is 2304077777655037952
Algorithm took 5828 nanoseconds
Result of iterative factorial 39 is 2304077777655037952
Algorithm took 5504 nanoseconds