Rabbit Counter Wraparound

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

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

You are building a test tool that jumps straight to any level, even level 1,000,000,000,000, and shows what the counter would read there. Playing through the levels one by one is not an option.

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 multiplied by itself 10 times is 1,024. A counter that wraps at 1,000 shows 1,024 − 1,000 = 24.

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

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

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

A trillion levels. Multiplying a trillion times would take far too long, but halving a trillion reaches 0 after about 40 steps, and each step needs 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. It is correct, but with up to 10¹⁵ levels that is 10¹⁵ multiplications. At a billion per second it would run for more than 11 days.

Computing the full power first and then taking the remainder is worse: 21,000,000,000,000 has hundreds of billions of digits, and in JavaScript 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