VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-exponentiation/

⇱ CSES Solutions - Exponentiation - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Exponentiation

Last Updated : 23 Jul, 2025

Your task is to efficiently calculate values a^b modulo 109+7. Note that in this task we assume that 00=1.

Examples:

Input: N = 3, queries[][] = {{3, 4}, {2, 8}, {123, 123}}
Output:
81
256
921450052
Explanation:

  • The first query is (3 ^ 4) % (109 + 7) = (3 * 3 * 3 * 3) % (109 + 7) = 81
  • The second query is (2 ^ 8) % (109 + 7) = (2 * 2 * 2 * 2 * 2 * 2 * 2 * 2) % (109 + 7) = 256
  • The third query is (123 ^ 123) % (109 + 7) = 921450052

Input: N = 2, queries[][] = {{4, 3}, {5, 3}}
Output:
64
125
Explanation:

  • The first query is (4 ^ 3) % (109 + 7) = (4 * 4 * 4) % (109 + 7) = 64
  • The second query is (5 ^ 3) % (109 + 7) = (5 * 5 * 5) % (109 + 7) = 125

Approach: To solve the problem, follow the below idea:

The idea is to uses the concept of binary exponentiation to do this efficiently. If the exponent is even, it squares the result of the base raised to half the exponent. If the exponent is odd, it multiplies the base with the square of the result of the base raised to half the exponent. This is done recursively until t he base case is reached.

Step-by-step algorithm:

  • Create a constant variable MOD with a value of 1000000007.
  • Create a function calPow() function to calculate the power of a number with modulo.
  • Use a recursive approach for efficient exponentiation.
  • Handles base cases for exponent == 0 and exponent == 1.
  • Calculates the power by dividing the exponent by 2 and squaring the result.
    • If the exponent is odd, it adjusts the calculation accordingly by multiplying the base.

Below is the implementation of the algorithm:


Output
81
256
921450052

Time Complexity: O(N * log(M)), where N is the number of queries and M is the maximum value of exponent.
Auxiliary Space: O(1)

Comment