The problem
You have as many coins of value a and of value b as you like. Return the number of ways to pay exactly amount: the number of pairs (x, y) of whole numbers, both 0 or more, with a * x + b * y == amount.
pay_ways(3, 5, 30) # 3: (10, 0), (5, 3), (0, 6)
pay_ways(4, 6, 9) # 0: 4x + 6y is always even
pay_ways(3, 5, 7) # 0
pay_ways(3, 5, 0) # 1: no coins
pow() is switched off for this problem, so its inverse shortcut (lesson 5) is not available: use the extended Euclidean algorithm from lesson 1.
Limits
aandbare from 1 to about 10¹⁸ (a 1 followed by 18 zeros);amountis from 0 to 10³⁶ (a 1 followed by 36 zeros).- Trying every number of a-coins is far too slow for big amounts. The tests with big numbers have 2 seconds each.
Builds on MATH-1 Divisibility and GCD.
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
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | The gcd does not divide | Not run | |
| 3 | Too small to pay | Not run | |
| 4 | Nothing to pay | Not run | |
| 5 | Two equal coins | Not run | |
| 6 | A coin of 1 | Not run | |
| 7 | A common divisor | Not run | |
| 8 | Every amount up to 40 | Not run | |
| 9 | Big coins | Not run | |
| 10 | Many ways | Not run | |
| 11 | Huge numbers | Not run | |
| 12 | Fibonacci coins | Not run |