With 3-cent and 5-cent stamps you can make every postage from 8 cents up, and the proof is a strong induction: if 8, 9 and 10 can be made, then every larger amount is one stamp more than a smaller one. Your program finds which amounts cannot be made with stamps of two values.
What to build
A program that lists the amounts up to N that cannot be paid with stamps of value a and b.
Requirements
- Read a, b and N on one line.
- An amount is makeable if it equals x × a + y × b for whole numbers x, y ≥ 0 (zero is makeable).
- Print
cannot make:followed by the amounts from 1 to N that are not makeable, in increasing order, separated by spaces, ornone. - Print
largest:and the largest such amount, ornone.
Input
One line with a, b and N.
Output
Two lines.
Constraints
1 ≤ a, b ≤ 20; 1 ≤ N ≤ 100.
Example
Input:
3 5 20
Output:
cannot make: 1 2 4 7
largest: 7
Why it works
Amount n can be made exactly when n is 0, or when n minus one stamp can be made: that is the inductive step, using a smaller case. Computing the answer for 0, 1, 2, ... in order is the same proof written as a loop, and the gaps are the amounts that no chain of stamps reaches.
Examples
3 5 20
cannot make: 1 2 4 7 largest: 7
4 7 30
cannot make: 1 2 3 5 6 9 10 13 17 largest: 17
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Mark 0 as makeable. An amount n is makeable if n - a is makeable or n - b is makeable.
Hint 2
This is a strong-induction idea: the step uses a smaller case, and the base case is 0.
Hint 3
Collect the amounts from 1 to N that are not makeable, in increasing order.
Solution
Show one correct solution (try it yourself first)
a, b, N = map(int, input().split())
ok = [False] * (N + 1)
ok[0] = True
for n in range(1, N + 1):
ok[n] = (n >= a and ok[n - a]) or (n >= b and ok[n - b])
bad = [n for n in range(1, N + 1) if not ok[n]]
print("cannot make:", " ".join(map(str, bad)) if bad else "none")
print("largest:", bad[-1] if bad else "none")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step