Intermediate Level

Implement the powIntegerFast method that calculates an integer power efficiently using fast exponentiation.

The input contains two integers: base and exponent. Your task is to calculate base raised to the power exponent.

The exponent is treated as a non-negative integer. For example, 2|10 means 2 multiplied by itself 10 times, so the result is 1024.

Example 1

Input
base (int) = 2
exponent (int) = 10
Returns (int) 1024

Example 2

Input
base (int) = 3
exponent (int) = 3
Returns (int) 27

Example 3

Input
base (int) = 5
exponent (int) = 0
Returns (int) 1

Use fast exponentiation instead of multiplying the base one time for every exponent value.

The idea is to repeatedly square the base and reduce the exponent by half. When the current exponent is odd, multiply the answer by the current base.

This reduces the number of operations from linear time to logarithmic time.

Pseudocode:

function powIntegerFast(base, exponent):
    result = 1
    while exponent > 0:
        if exponent is odd:
            result = result * base
        base = base * base
        exponent = exponent / 2
    return result
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.