You get a positive whole number a and a huge exponent b, written as a list of its decimal digits, most significant first. Work out a raised to the power b, and return only its remainder after dividing by 1337.
The exponent can have 2,000 digits, so it never fits in a normal integer, and the power itself is far too large to build.
Example 1
Input: a = 3, b = [1, 5] Output: 223 Why: 3¹⁵ = 14,348,907, which leaves 223 when divided by 1337
2 more examples and the constraints
Example 2
Input: a = 5, b = [2, 4, 0] Output: 414 Why: 5²⁴⁰ mod 1337, reached without ever writing 5²⁴⁰ out
Example 3
Input: a = 2674, b = [3] Output: 0 Why: 2674 = 2 · 1337, so every power of it is a multiple of 1337
Constraints
- 1 ≤ a ≤ 2,147,483,647
- 1 ≤ length of b ≤ 2,000, and every b[i] is a digit from 0 to 9
- b has no leading zeros
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Digit by digitO(n)
- Shrink the exponentO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 2,000-digit exponent | Verdict |
|---|---|---|---|
| Digit by digit | O(n) | Passes; no theory needed | |
| Shrink the exponent | O(n) | Best; one fold, one power |
n = number of digits in b.
Edge cases to test
- a is a multiple of 1337. 2674 with b = [3] gives 0.
- Exponent 0. b = [0] means a⁰, which is 1.
- Exponent a multiple of 570. a = 7, b = [5, 7, 0] must not collapse to a⁰; the answer is 7⁵⁷⁰ mod 1337.
- Largest a. 2,147,483,647 times itself overflows 32 bits, so reduce a mod 1337 before multiplying.
Common mistakes
- Multiplying before reducing a, so a · a overflows a 32-bit int.
- Reducing the exponent mod 1336 or 1337 instead of a true period such as 570 or 1140.
- Turning e = 0 into a⁰ = 1 when b is a nonzero multiple of the period.
How to talk through it
- 1Clarify. Is the modulus always 1337? Can b be [0]? Is a reduced already?
- 2Give the digit method. a^(10e + d) = (a^e)^10 · a^d, so one pass over the digits works.
- 3Find the period. 1337 = 7 · 191; powers repeat every lcm(6, 190) = 570 steps.
- 4Code the fold and fast power. Mod 570 per digit, fix e = 0, then square and multiply.
- 5Test out loud. Run a = 2674, b = [0] and a = 7 with b = 570 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?