Todos los desafíos
Fácil 0 resueltos 0% de aceptación

Power by Repeated Multiplication

Raise a number to a power with a loop.

Lo que aprenderás

  • Multiply repeatedly in a loop
  • Handle an exponent of zero
  • Compare with the built-in power

Problema

Ver traducción

Compute base to the power exponent by multiplying base by itself exponent times in a loop. Any number to the power 0 is 1.

Implement power(base, exponent).

Input

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

Output

Return base raised to exponent.

Restricciones

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

Ejemplos

Ejemplo 1
Entrada:
base = 2
exponent = 10

Salida esperada:
expected = 1024
Entrada:
long long base = 2;
long long exponent = 10;

Salida esperada:
long long expected = 1024;
Entrada:
long base = 2;
long exponent = 10;

Salida esperada:
long expected = 1024;

Explicación

2 multiplied by itself 10 times is 1024.

Ejemplo 2
Entrada:
base = 5
exponent = 0

Salida esperada:
expected = 1
Entrada:
long long base = 5;
long long exponent = 0;

Salida esperada:
long long expected = 1;
Entrada:
long base = 5;
long exponent = 0;

Salida esperada:
long expected = 1;

Explicación

Anything to the power 0 is 1.

Cómo abordarlo

Inténtalo primero por tu cuenta y luego abre las pistas una a una.

Pista 1

The exponent tells you how many times to keep multiplying the base into an accumulating result.

Pista 2

Start from the neutral value for multiplication so the zero-exponent case works naturally.

Pista 3

Watch for the edge case where the exponent is zero, since no looping should still give a valid answer.

Complejidad esperada

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

Referencias

Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.

Aprende de otros

Soluciones de la comunidad

Aún no hay soluciones publicadas. Resuelve este reto para compartir la primera.