Lesson 4.5 · Write it
Integer power
A functionPython or Java7 tests, 4 of them hidden
On a phone? Put the lines in order instead
Write a function that returns base raised to the power exponent, using a loop, not a built-in power function.
baseandexponentare whole numbers, chosen so that the answer is from -1000000000 to 1000000000, andexponentis at most 100.exponentis always 0 or positive.- Anything raised to the power 0 is 1.
- Do not use
**(Python) orMath.pow(Java).
Only the number your function returns is checked.
def int_power(base: int, exponent: int) -> int
You cannot use these in this question:
- pow()
- .__pow__()
- import math
- import cmath
This question is about writing the loop yourself, so built-in power functions are not allowed.
Examples
Your function is tested on 7 cases: the 3 examples below, and 4 hidden ones that check the rules above.
- int_power(2, 3) should return 8: 2 cubed is 8 (rule 1)
- int_power(5, 0) should return 1: anything to the power 0 is 1 (rule 3)
- int_power(3, 2) should return 9: 3 squared is 9 (rule 1)
public static int intPower(int base, int exponent)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.Checking whether Java answers can run here.
You cannot use these in this question:
- Math.pow()
This question is about writing the loop yourself, so built-in power functions are not allowed.
Examples
Your function is tested on 7 cases: the 3 examples below, and 4 hidden ones that check the rules above.
- intPower(2, 3) should return 8: 2 cubed is 8 (rule 1)
- intPower(5, 0) should return 1: anything to the power 0 is 1 (rule 3)
- intPower(3, 2) should return 9: 3 squared is 9 (rule 1)