Connect with us


Power – Mod Power – HackerRank Python Solution

This Python solution demonstrates how to compute power and modular power efficiently (modular exponentiation).



In this post, I will explain my simple Python solution to the HackerRank problem “Power – Mod Power.” The problem requires us to calculate two values: the power of a number and the power of a number modulo another number (also known as modular exponentiation). We commonly use the modulo operator for such tasks (%), however it is not necessary for this HackerRank problem. Instead, my solution accomplishes this using the pow() function in Python.

# Full Python solution to "Power - Mod Power" from HackerRank.
a = int(input())
b = int(input())
m = int(input())

print(pow(a, b))
print(pow(a, b, m))

First, the code reads three integers from the user, via the input() function. Notice that it converts each input into an integer using int(). The first integer, a, is the base number. The second integer, b, is the exponent. The third integer, m, is the modulus.

The code calculates the power of the value of a raised to the value of b using Python’s built-in pow() function. This function is called with two arguments here, a and b, and computes a ^ b. The result is printed directly, without needing an additional variable for storage.

After that, the code calculates the power of a raised to b modulo m using the three-argument form of Python’s pow() function. This calculates a ^ b mod m in a more efficient manner than computing a ^ b first and then taking the modulus, especially for large numbers. The result of this operation is printed on the second line on the console.