MATH-P1

Paying with two coins

Practice 1 of 7Number theory and counting12 tests

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

  • a and b are from 1 to about 10¹⁸ (a 1 followed by 18 zeros); amount is 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

  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.

12 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2The gcd does not divideNot run
3Too small to payNot run
4Nothing to payNot run
5Two equal coinsNot run
6A coin of 1Not run
7A common divisorNot run
8Every amount up to 40Not run
9Big coinsNot run
10Many waysNot run
11Huge numbersNot run
12Fibonacci coinsNot run