我正在比较在 Java 中计算迭代和递归阶乘过程的时间。我正在尝试使用该System.currentTimeMillis
方法来比较每种算法计算所需的时间,但我似乎无法计算出差异。我不确定使用此方法的正确方法是什么,但这里的任何事件都是我试图在我的代码中实现的:
// ... 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
这是输出:
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
显然我在这里做错了,因为计算这两种情况的阶乘的预期时间不应该为零。
编辑:如果有人感兴趣,这是我的阶乘解决方案(不是特别独特,但无论如何它们都在这里):
// 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;
}
并且是一些输出。令人惊讶的是,递归版本的效果很好。还没到39点左右!迭代版本开始表现得明显更好。
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