Rabbit Counter Wraparound

EasyrecursionAlso known as Pow(x, n) / Modular Exponentiation

In a retro arcade game you start with 1 rabbit, and each level you clear multiplies your rabbits by factor. The old counter wraps like a car odometer: when it would reach wrap, it restarts from 0. So the screen shows the true count's remainder after dividing by wrap.

Your test tool must jump straight to any level, even level 1,000,000,000,000, and show the counter there, without playing through.

Your task

Write counterAt(factor, levels, wrap). Return factorlevels modulo wrap: the remainder of the true rabbit count after levels levels, divided by wrap.

With 0 levels the count is 1 (even when factor is 0), so return 1 % wrap. The answer is always between 0 and wrap − 1.

counterAt(factor: int, levels: int, wrap: int) → int

Examples

Example 1
Input
factor = 2
levels = 10
wrap = 1000
Output
24
Why

2¹⁰ = 1,024. A counter that wraps at 1,000 shows 24.

Example 2
Input
factor = 3
levels = 13
wrap = 100
Output
23
Why

3¹³ = 1,594,323, which leaves 23 after dividing by 100. You do not need the full number: 3⁶ leaves 29, and 29 × 29 × 3 = 2,523 also leaves 23.

Example 3
Input
factor = 2
levels = 1000000000000
wrap = 1000000
Output
109376
Why

Multiplying a trillion times would take far too long, but halving a trillion reaches 0 in about 40 steps, each needing at most two multiplications.

Constraints

  • 0 ≤ factor ≤ 1,000,000,000
  • 0 ≤ levels ≤ 1,000,000,000,000,000
  • 1 ≤ wrap ≤ 1,000,000
Start with brute force

Start at 1 and multiply by factor once per level, taking the remainder each time. This is correct, but with up to 10¹⁵ levels it needs 10¹⁵ multiplications, which takes over 11 days at a billion per second.

Computing the full power and then the remainder is worse: 21,000,000,000,000 has hundreds of billions of digits, and JavaScript's Math.pow loses exact digits long before that (already at 3⁴⁰).

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code