Tutte le sfide
Media 0 risolte 0% di accettazione

Recursive Power

Compute a power recursively by halving the exponent.

Problema

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.

Vincoli

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

Esempi

Esempio 1
Input:
base = 3
exponent = 5

Output atteso:
expected = 243
Input:
long long base = 3;
long long exponent = 5;

Output atteso:
long long expected = 243;
Input:
long base = 3;
long exponent = 5;

Output atteso:
long expected = 243;

Spiegazione

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

Esempio 2
Input:
base = 7
exponent = 0

Output atteso:
expected = 1
Input:
long long base = 7;
long long exponent = 0;

Output atteso:
long long expected = 1;
Input:
long base = 7;
long exponent = 0;

Output atteso:
long expected = 1;

Spiegazione

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.