Super Pow - Problem
Super Power Modulo Challenge

You need to calculate ab mod 1337 where:
โ€ข a is a positive integer
โ€ข b is an extremely large positive integer given as an array of digits

The challenge here is that b can be so large that it won't fit in any standard integer type! For example, b could be represented as [1,2,3,4,5,6,7,8,9,0] meaning the number 1234567890.

Goal: Efficiently compute the modular exponentiation without overflow
Input: Integer a and array b representing a huge number
Output: ab mod 1337 as an integer

Input & Output

example_1.py โ€” Basic Case
$ Input: a = 2, b = [3]
โ€บ Output: 8
๐Ÿ’ก Note: 2^3 = 8, and 8 mod 1337 = 8
example_2.py โ€” Large Exponent
$ Input: a = 2, b = [1,0]
โ€บ Output: 1024
๐Ÿ’ก Note: 2^10 = 1024, and 1024 mod 1337 = 1024
example_3.py โ€” Modulo Effect
$ Input: a = 2147483647, b = [2,0,0]
โ€บ Output: 1198
๐Ÿ’ก Note: 2147483647^200 mod 1337 = 1198 (demonstrates the modulo effect)

Constraints

  • 1 โ‰ค a โ‰ค 231 - 1
  • 1 โ‰ค b.length โ‰ค 2000
  • 0 โ‰ค b[i] โ‰ค 9
  • b doesn't contain leading zeros
  • The result should be computed modulo 1337

Visualization

Tap to expand
Super Pow Solution Visualizationa^[1,2,3,4,5](Original Problem)(a^[1,2,3,4])^10a^5(a^[1,2,3])^10a^4ร—ร—mod 1337at each stepโœ“ No overflow, handles any size exponent!Time: O(n), Space: O(n)
Understanding the Visualization
1
Recursive Decomposition
Break a^[1,2,3,4] into (a^[1,2,3])^10 * a^4
2
Apply Modular Arithmetic
Use (x*y) mod m = ((x mod m) * (y mod m)) mod m
3
Prevent Overflow
Each intermediate result stays within bounds
Key Takeaway
๐ŸŽฏ Key Insight: Use the mathematical property a^[d1,d2,d3] = (a^[d1,d2])^10 * a^d3 combined with modular arithmetic to handle arbitrarily large exponents efficiently!
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 5
24.6K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen