MATH-P3

The footbridge, 10¹⁸ steps

Practice 3 of 7Number theory and counting13 tests

The problem

RECR-P2 counted the ways to go up a footbridge of n steps with moves of 1, 2 or 3. Now the allowed moves are given in the list steps, and n can be enormous. Return the number of different sequences of moves that end exactly at the top, modulo m (the remainder after dividing by m).

ways_mod(4, [1, 2, 3], 1000)     # 7
ways_mod(10, [1, 2], 10 ** 9)    # 89
ways_mod(7, [2], 100)            # 0
ways_mod(0, [1, 2, 3], 1000)     # 1

Limits

  • n is from 0 to 10¹⁸ (a 1 followed by 18 zeros). steps holds 1 to 10 different moves, each from 1 to 10. m is from 1 to about 10¹⁸.
  • A loop over every step is far too slow for n = 10¹⁸. The big tests have 2 seconds each.

Builds on MATH-3 Fast exponentiation.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

13 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2No steps to go upNot run
3m is 1Not run
4FibonacciNot run
5Only 2s, odd nNot run
6Only 2s, even nNot run
7Moves of 3 and 5Not run
8The first 20Not run
9A million stepsNot run
1010¹⁸ stepsNot run
11Ten moves, a huge mNot run
12Unusual movesNot run
13The last digit of a Fibonacci numberNot run