InferenceAI

Enter at least two characters to search.

Start free

Modular Power

mediumMath25 min25 XP

Return ab mod ma^b \bmod m without using the built-in three-argument pow.

Requirements

  • Run in O(log⁡b)O(\log b) multiplications using exponentiation by squaring:
ab={(ab/2)2b evena⋅ab−1b odda^{b} = \begin{cases} \left(a^{b/2}\right)^2 & b \text{ even} \\ a \cdot a^{b-1} & b \text{ odd} \end{cases}

Constraints

  • 0≤a,b≤10180 \le a, b \le 10^{18}, 1≤m≤1091 \le m \le 10^9

Examples

EXAMPLE WALKTHROUGH1024 mod 1000

A guided view of the published example, not a trace of your code.

INPUT[2,10,1000]
TASKmodular_power()
EXPECTED OUTPUT24

Start with the input values shown in this example.

Example 1 of 3

Input: a = 2, b = 10, m = 1000

Output: 24

Explanation: 1024 mod 1000

Input: a = 3, b = 0, m = 7

Output: 1

Explanation: zero exponent

Input: a = 7, b = 128, m = 13

Output: 3

Explanation: power of two exponent

Hint 1

Look at the bits of b from least to most significant, squaring the base each step.

Topics

DSAMathPython