pow(exponent) メソッドでいくつかのテストを行いました。残念ながら、私の数学のスキルは、次の問題を処理できるほど強力ではありません。
私はこのコードを使用しています:
BigInteger.valueOf(2).pow(var);
結果:
- 変数 | 時間 (ミリ秒)
- 2000000 | 11450
- 2500000 | 12471
- 3000000 | 22379
- 3500000 | 32147
- 4000000 | 46270
- 4500000 | 31459
- 5000000 | 49922
見る?2,500,000 の指数は、2,000,000 とほぼ同じ速さで計算されます。4,500,000 は、4,000,000 よりもはるかに高速に計算されます。
何故ですか?
参考までに、BigInteger.pow(exponent) の元の実装を次に示します。
public BigInteger pow(int exponent) {
if (exponent < 0)
throw new ArithmeticException("Negative exponent");
if (signum==0)
return (exponent==0 ? ONE : this);
// Perform exponentiation using repeated squaring trick
int newSign = (signum<0 && (exponent&1)==1 ? -1 : 1);
int[] baseToPow2 = this.mag;
int[] result = {1};
while (exponent != 0) {
if ((exponent & 1)==1) {
result = multiplyToLen(result, result.length,
baseToPow2, baseToPow2.length, null);
result = trustedStripLeadingZeroInts(result);
}
if ((exponent >>>= 1) != 0) {
baseToPow2 = squareToLen(baseToPow2, baseToPow2.length, null);
baseToPow2 = trustedStripLeadingZeroInts(baseToPow2);
}
}
return new BigInteger(result, newSign);
}