RECR-P1

Power on a clock

Practice 1 of 6Recursion and backtracking8 tests

The problem

A clock with m hours wraps round to 0 after m - 1. Working “on the clock” means keeping only the remainder after dividing by m. Return x to the power n, on a clock of m: that is, (x ** n) % m.

power_mod(3, 4, 5)       # 81 % 5 = 1
power_mod(2, 13, 1000)   # 8192 % 1000 = 192
power_mod(7, 0, 13)      # 1

pow() is switched off for this problem. x ** n works for small n, but for n = 10¹⁸ (a 1 followed by 18 zeros) the number could have about 9 billion billion digits, far more than any computer can store.

Limits

  • x is from 0 to 10⁹ (a billion), n from 0 to 10¹⁸ (a billion billion), and m from 1 to 10⁹.

Builds on RECR-1 Base case and recursive case and RECR-2 The call stack.

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.

8 tests, not run yet
Test results
#TestResultReads · time
1SmallNot run
2Odd powerNot run
3Power 0Not run
4Modulus 1Not run
5x bigger than mNot run
6x is 0Not run
7n = 10⁹Not run
8n = 10¹⁸Not run