中級 0件解決済み 正答率0%

Recursive Power

Compute a power recursively by halving the exponent.

問題

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.

参考資料

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

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。