Super Pow - Problem

Your task is to calculate a^b mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.

For example, if a = 2 and b = [3], then b represents the number 3, so we need to calculate 2^3 mod 1337 = 8.

If a = 2 and b = [1,0], then b represents the number 10, so we need to calculate 2^10 mod 1337 = 1024.

Note: a and elements of b are guaranteed to be positive integers.

Input & Output

Example 1 — Basic Single Digit
$ Input: a = 2, b = [3]
Output: 8
💡 Note: b represents the number 3, so we calculate 2^3 mod 1337 = 8 mod 1337 = 8
Example 2 — Multi-digit Exponent
$ Input: a = 2, b = [1,0]
Output: 1024
💡 Note: b represents the number 10, so we calculate 2^10 mod 1337 = 1024 mod 1337 = 1024
Example 3 — Large Base with Modulo Effect
$ Input: a = 2147483647, b = [2]
Output: 1198
💡 Note: Large base: (2147483647^2) mod 1337. First reduce base: 2147483647 mod 1337 = 1198, then 1198^2 mod 1337 = 1198

Constraints

  • 1 ≤ a ≤ 231 - 1
  • 1 ≤ b.length ≤ 2000
  • 0 ≤ b[i] ≤ 9
  • b does not contain leading zeros except for the number 0 itself

Visualization

Tap to expand
Super Pow - Chinese Remainder Theorem INPUT Base number: a 2 Exponent array: b [3] Modulo: 1337 1337 = 7 × 191 Calculate: 2^3 mod 1337 b represents number 3 ALGORITHM STEPS 1 Factor 1337 1337 = 7 × 191 (coprime) 2 Compute mod 7 2^3 mod 7 = 8 mod 7 = 1 3 Compute mod 191 2^3 mod 191 = 8 mod 191 = 8 4 Apply CRT Combine results using CRT Chinese Remainder Theorem: x ≡ 1 (mod 7) x ≡ 8 (mod 191) x = 8 (mod 1337) FINAL RESULT Output: 8 Verification: 2^3 = 8 8 mod 1337 = 8 [OK] Result verified! 8 mod 7 = 1 Complexity: Time: O(n log m) Space: O(1) Key Insight: Since 1337 = 7 × 191 (two coprime factors), we can use Chinese Remainder Theorem to split the modular exponentiation into two smaller problems. Computing a^b mod 7 and a^b mod 191 separately is more efficient, then combine results with CRT. Uses Euler's theorem for optimization. TutorialsPoint - Super Pow | Chinese Remainder Theorem Optimization
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
89.0K Views
Medium Frequency
~35 min Avg. Time
856 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