中級 2件解決済み 正答率100.0%

Recursive Power

Compute a power recursively by halving the exponent.

このチャレンジで学べること

  • Halve the exponent each call
  • Write base cases for recursion
  • Go from linear to logarithmic time

問題

翻訳を表示

Compute base to the power exponent with recursion: x⁰ = 1, and xⁿ = (x^(n/2))² for even n or x × (x^((n−1)/2))² for odd n. This uses far fewer multiplications than a simple loop.

Implement recursive_power(base, exponent).

Input

base: The base. exponent: The exponent (zero or positive).

Output

Return base raised to exponent.

制約

-10 ≤ base ≤ 10; 0 ≤ exponent ≤ 18

例

例 1
入力:
base = 3
exponent = 5

期待される出力:
expected = 243
入力:
long long base = 3;
long long exponent = 5;

期待される出力:
long long expected = 243;
入力:
long base = 3;
long exponent = 5;

期待される出力:
long expected = 243;

解説

3⁵ = 3 × (3²)² = 3 × 81 = 243.

例 2
入力:
base = 7
exponent = 0

期待される出力:
expected = 1
入力:
long long base = 7;
long long exponent = 0;

期待される出力:
long long expected = 1;
入力:
long base = 7;
long exponent = 0;

期待される出力:
long expected = 1;

解説

The base case: anything to the power 0 is 1.

解き方のヒント

まずは自分で考えてから、ヒントを1つずつ開いてみましょう。

ヒント 1

Use the exponent’s parity to shrink the problem size quickly.

ヒント 2

Recursive squaring avoids repeating work and cuts the number of multiplications drastically.

ヒント 3

Be careful with the zero exponent and the base case for tiny exponents.

目安の計算量

O(log exponent) time, O(log exponent) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 Н"Никита "Programmer" Python 820 ms - 5/5 コードを見る
2 LMLaura Mahlow Python 829 ms - 3/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意: この下に解答が2件あります まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。