Math Fundamentals18 sections · 814 units
Open in Course

Super Pow - Implementation

The pseudocode

Here is the full solution:


function superPow(a, b)
    MOD := 1337
    result := 1
    a := a mod MOD
    for each digit d in b
        result := (pow(result, 10, MOD) * pow(a, d, MOD)) mod MOD
    return result

function pow(base, exp, mod)
    result := 1
    base := base mod mod
    while exp > 0
        if exp mod 2 = 1 then
            result := (result * base) mod mod
        exp := exp / 2
        base := (base * base) mod mod
    return result

Time: O(nlog10)O(n \log 10) where nn is the number of digits in bb. Space: O(1)O(1).