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