Minimum Threshold for 5-and-21 Integer Combinations
Medium · Coding & Algorithms · Data Scientist · Online Assessment
Problem Statement
Consider building integers by combining any non-negative number of 5s and 21s. Specifically, an integer x is called achievable if there exist integers a >= 0 and b >= 0 such that:
x = 5 * a + 21 * b
Using zero copies of either value is valid (for instance, 5 = 5 * 1 + 21 * 0 and 21 = 5 * 0 + 21 * 1 are both achievable).
Implement smallest_n_for_5_and_21_sums() to compute and return the minimum positive integer N with the guarantee that every integer x >= N (N, N + 1, N + 2, ... without exception) is achievable.
Examples
Example 1
Checking individual candidate totals with building blocks 5 and 21:
x = 57 -> achievable, since 57 = 3 * 5 + 2 * 21 (15 + 42)
x = 29 -> NOT achievable:
b = 0 gives remainder 29 - 0 = 29 (not divisible by 5)
b = 1 gives remainder 29 - 21 = 8 (not divisible by 5)
b >= 2 exceeds 29 (2 * 21 = 42 > 29)
Explanation: Because 29 cannot be written as 5 * a + 21 * b for non-negative integers a and b, the cutoff N for (5, 21) must be strictly greater than 29.
Example 2
Illustrating the threshold definition on a smaller analogous pair (3, 7) instead of (5, 21):
Building blocks: (3, 7)
x = 11 -> NOT achievable (neither 11 nor 11 - 7 = 4 is divisible by 3)
x = 12 -> 4 * 3 + 0 * 7
x = 13 -> 2 * 3 + 1 * 7
x = 14 -> 0 * 3 + 2 * 7
Explanation: Once three consecutive integers (12, 13, 14) are achievable using 3 and 7, every larger integer follows by repeatedly adding 3, making 12 the minimum threshold for (3, 7). Calling smallest_n_for_5_and_21_sums() returns the corresponding minimum threshold N for (5, 21).
Constraints
- Multipliers
aandbmust be non-negative integers (a >= 0,b >= 0). smallest_n_for_5_and_21_sums()takes zero arguments and returns a Pythonint.
Step-by-step walkthrough
Restate the problem and check when an answer exists
We call an integer
xachievable if we can build it by adding some non-negative number of5s and some non-negative number of21s:x = 5 * a + 21 * b where a >= 0 and b >= 0 are integersUsing zero of one kind is allowed:
5 = 5 * 1 + 21 * 0and21 = 5 * 0 + 21 * 1are both achievable, as is57 = 5 * 3 + 21 * 2from Example 1. We wantsmallest_n_for_5_and_21_sums()to return the minimum positive integerNsuch that every integer fromNonward (N, N + 1, N + 2, ...forever) is achievable.Rather than returning a hardcoded magic constant with no explanation, we will write a clean general function
smallest_always_representable(a, b)and call it with(5, 21).First, verify why a finite cutoff
Nexists at all: -5and21are coprime, meaning their greatest common divisor (gcd(5, 21), the largest integer dividing both evenly) is1. - If two denominations shared a factor bigger than1— say4and6(gcd = 2) — then4 * a + 6 * bwould always be even, so odd numbers would fail forever and no finiteNwould exist.Brute force for one target, and why we need a stopping rule
To test whether a single target
xis achievable, we can try every valid countbof21s (b = 0, 1, ..., x // 21) and check whether the leftoverx - 21 * bis divisible by5:Example 1 check (x = 29): b = 0 -> leftover 29 (not divisible by 5) b = 1 -> leftover 8 (not divisible by 5) => 29 is NOT achievable! Later gap check (x = 79): b = 0 -> leftover 79 (not divisible by 5) b = 1 -> leftover 58 (not divisible by 5) b = 2 -> leftover 37 (not divisible by 5) b = 3 -> leftover 16 (not divisible by 5) => 79 is NOT achievable either!We can scan
x = 1, 2, 3, ...upward, spotting which numbers work and which fail. However, the problem asks about every integer>= N— an infinite set of numbers! How do we know with 100% certainty when the gaps have ended forever?Key idea: five consecutive achievable numbers unlock everything above
Just like Example 2 showed
3consecutive hits (12, 13, 14) unlocking everything above12for(3, 7), suppose we find 5 achievable integers in a row for(5, 21):m, m + 1, m + 2, m + 3, m + 4. What happens to the next 5 integers after them?Base streak of 5: m m+1 m+2 m+3 m+4 (all achievable) Add one 5 (+5): m+5 m+6 m+7 m+8 m+9 (all achievable!) Add another 5 (+5): m+10 m+11 m+12 m+13 m+14 (all achievable!) ... ... ... ... ... ... (forever!)Adding
5to an achievable number simply increases its multiplieraby1, so the result is guaranteed to be achievable too! Thus, the very first time our upward scan seesmin(a, b)(here5) achievable numbers in a row:- Everything from the start of that streak (
m) onward is achievable, because+5tiles every larger integer without leaving gaps. - No smaller starting value works, because
m - 1was not achievable (ifm - 1had been achievable, the streak of5would have completed one step earlier!).
So
mis provably the exact minimalN.- Everything from the start of that streak (
Fast dynamic programming check as we scan upward
Instead of re-checking every multiple of
21from scratch at eachx, we can use dynamic programming (solving each number inO(1)time by looking up smaller numbers we already solved).Think about the last piece added to form a positive total
v: - Either the combination uses at least one5, meaningv - 5is also a valid combination of5s and21s; - Or the combination uses at least one21, meaningv - 21is also a valid combination of5s and21s.Seeding
can_make[0] = True(since0 = 5 * 0 + 21 * 0uses zero pieces), each new integervonly needs two boolean lookups:can_make[v - 5]andcan_make[v - 21].Verify by hand using remainders modulo 5
Before coding, we can predict the exact answer on paper using remainders modulo 5 (the leftover after dividing by
5).Adding
5s never changes a number's remainder modulo5. Meanwhile,21 = 4 * 5 + 1adds1to the remainder modulo5. Here is the smallest achievable non-negative integer in each of the five remainder lanes0, 1, 2, 3, 4:Remainder mod 5 | Minimum copies of 21 needed | Smallest achievable value | Values in this lane ----------------+-----------------------------+---------------------------+------------------------- 0 | 0 copies (0 * 21) | 0 | 0, 5, 10, 15, ... 1 | 1 copy (1 * 21) | 21 | 21, 26, 31, 36, ... 2 | 2 copies (2 * 21) | 42 | 42, 47, 52, 57, ... 3 | 3 copies (3 * 21) | 63 | 63, 68, 73, 78, ... 4 | 4 copies (4 * 21) | 84 | 84, 89, 94, 104, ...Look at the slowest lane — remainder
4: - Its very first achievable value is84(notice how29from Example 1 sits in lane4well below84, which is why29failed!). - One step below84in lane4is84 - 5 = 79, which is unreachable! - Every integer>= 80sits at or above its lane's starting value (80in lane0,81in lane1,82in lane2,83in lane3,84in lane4).Therefore,
79is the largest unreachable integer, andN = 80. (In general, for any coprime integersa, b >= 2, the largest unreachable integer isa * b - a - b, givingN = a * b - a - b + 1 = 5 * 21 - 5 - 21 + 1 = 80— matching3 * 7 - 3 - 7 + 1 = 12from Example 2!)Code the scan and trace around N = 80
Let's translate the upward scan into clean Python and watch how
consecutive_runbehaves right around80:current_value: 74 75 76 77 78 79 80 81 82 83 84 is_reachable: F T T T T F T T T T T consecutive_run: 0 1 2 3 4 0 1 2 3 4 5 <-- hits 5! Return: current_value - smaller_coin + 1 = 84 - 5 + 1 = 80Notice how
75, 76, 77, 78reach a streak of4— just one short — before79resetsconsecutive_runto0. Then80, 81, 82, 83, 84hit a full streak of5, stopping the loop atcurrent_value = 84and returning80.from math import gcd def smallest_always_representable(a: int, b: int) -> int: # Guard: if a and b share a common factor > 1 (e.g., 4 and 6), every sum # is a multiple of gcd(a, b), so non-multiples are unreachable forever. if a < 1 or b < 1 or gcd(a, b) != 1: raise ValueError("a and b must be positive and coprime") # smaller_coin: once this many consecutive integers are representable, # every larger integer can be formed by adding copies of smaller_coin. smaller_coin = min(a, b) # can_make: boolean list where can_make[v] is True iff v = a*x + b*y # for non-negative integers x, y; seeded with 0 = a*0 + b*0. can_make = [True] # consecutive_run: how many integers in a row ending at current_value are True. consecutive_run = 0 current_value = 0 # Scan upward one integer at a time until we hit a full run of length smaller_coin. while consecutive_run < smaller_coin: current_value += 1 # A positive value v is representable iff removing one 'a' or one 'b' # lands on an already-representable non-negative value. reachable_via_a = current_value >= a and can_make[current_value - a] reachable_via_b = current_value >= b and can_make[current_value - b] is_reachable = reachable_via_a or reachable_via_b can_make.append(is_reachable) if is_reachable: consecutive_run += 1 else: # A gap breaks the streak; any valid N must start strictly after this value. consecutive_run = 0 # current_value is the LAST element of a run of length smaller_coin, # so subtracting (smaller_coin - 1) gives the FIRST element of that run. return current_value - smaller_coin + 1Complete solution
Wrapping the helper inside the judged function
smallest_n_for_5_and_21_sums():from typing import Any, Dict, List, Optional, Set, Tuple from math import gcd def smallest_n_for_5_and_21_sums() -> int: # Solve the specific (5, 21) problem via the general two-coin scan helper. return smallest_always_representable(5, 21) def smallest_always_representable(a: int, b: int) -> int: # Guard: if a and b share a common factor > 1 (e.g., 4 and 6), every sum # is a multiple of gcd(a, b), so non-multiples are unreachable forever. if a < 1 or b < 1 or gcd(a, b) != 1: raise ValueError("a and b must be positive and coprime") # smaller_coin: once this many consecutive integers are representable, # every larger integer can be formed by adding copies of smaller_coin. smaller_coin = min(a, b) # can_make: boolean list where can_make[v] is True iff v = a*x + b*y # for non-negative integers x, y; seeded with 0 = a*0 + b*0. can_make = [True] # consecutive_run: how many integers in a row ending at current_value are True. consecutive_run = 0 current_value = 0 # Scan upward one integer at a time until we hit a full run of length smaller_coin. while consecutive_run < smaller_coin: current_value += 1 # A positive value v is representable iff removing one 'a' or one 'b' # lands on an already-representable non-negative value. reachable_via_a = current_value >= a and can_make[current_value - a] reachable_via_b = current_value >= b and can_make[current_value - b] is_reachable = reachable_via_a or reachable_via_b can_make.append(is_reachable) if is_reachable: consecutive_run += 1 else: # A gap breaks the streak; any valid N must start strictly after this value. consecutive_run = 0 # current_value is the LAST element of a run of length smaller_coin, # so subtracting (smaller_coin - 1) gives the FIRST element of that run. return current_value - smaller_coin + 1The minimum integer
Nfrom which every integer is achievable is80.✅ Submit now — all tests should pass.
Intuition & how it works
Imagine weighing parcels on a balance using only 5-gram and 21-gram weights. Some totals like 57 = 3 * 5 + 2 * 21 work cleanly, while others like 29 or 79 cannot be formed at all, leaving gaps along the number line. However, the exact moment you can form 5 consecutive integers in a row (m, m + 1, m + 2, m + 3, m + 4), gaps disappear forever — because you can form the next 5 integers (m + 5 through m + 9) simply by adding one 5-gram weight to each of those 5 totals, and keep stepping forward by +5 endlessly! (Just as in Example 2, where hitting 3 consecutive achievable values 12, 13, 14 with (3, 7) unlocked every integer >= 12.)
A naive approach checks numbers up to an arbitrary ceiling like 1,000 by trying every count of 21s for each candidate. That approach has two flaws: without the "5-in-a-row" stopping rule, you have no mathematical guarantee that another gap isn't hiding beyond 1,000, and testing every multiple of 21 from scratch repeats work we already completed. Instead, we use dynamic programming (storing boolean answers for smaller integers in a list so each new integer is solved in constant time): a positive integer v is achievable if and only if v - 5 or v - 21 was already achievable.
Watch how the upward scan finishes right around the threshold:
1. At 75, 76, 77, 78, we hit four achievable integers in a row (15 * 5, 21 + 11 * 5, 2 * 21 + 7 * 5, 3 * 21 + 3 * 5), then 79 fails because subtracting 0, 1, 2, or 3 copies of 21 leaves 79, 58, 37, 16 — none divisible by 5 — resetting the streak to 0.
2. Next come 80 = 16 * 5, 81 = 21 + 12 * 5, 82 = 2 * 21 + 8 * 5, 83 = 3 * 21 + 4 * 5, and 84 = 4 * 21: 5 achievable integers in a row!
3. The loop stops at 84 and returns the start of that 5-integer streak, 84 - 5 + 1 = 80.
Complexity
- Time:
O(a * b)for the general helpersmallest_always_representable(a, b)(which isO(1)for the fixed pair(5, 21), executing only84loop iterations). Each integer up toa * b - max(a, b)is visited once and checked with twoO(1)list lookups. (Using the two-denomination closed forma * b - a - b + 1directly takesO(1)arithmetic for any coprimea, b >= 2, while the DP scan derives the answer from first principles without memorizing a formula.) - Space:
O(a * b)for thecan_makeboolean list (85booleans for5and21). Because each step only looks back atv - aandv - b, a sliding ring buffer of sizemax(a, b)could shrink auxiliary memory toO(max(a, b))for very large inputs.
Edge cases
- Zero copies of one building block (
a = 0orb = 0): Totals like5 = 1 * 5 + 0 * 21and21 = 0 * 5 + 1 * 21are valid; seedingcan_make[0] = Trueensurescan_make[5]andcan_make[21]both evaluate toTrue. - Zero itself (
0):0 = 0 * 5 + 0 * 21seeds the dynamic programming table, while the upward scan starts testing positive integers atcurrent_value = 1. - Non-coprime inputs (e.g.,
4and6): Two integers are coprime when their greatest common divisor (gcd, the largest integer dividing both evenly) is1. Whengcd(a, b) > 1, only multiples of that divisor can ever be formed, sosmallest_always_representableraisesValueErrorinstead of looping forever. - Unit denomination (
1and21): Every positive integer is immediately achievable using copies of1; atcurrent_value = 1the streak hitsmin(1, 21) = 1and the helper returns1.
Common mistakes
- Returning
79instead of80:79is the Frobenius number (the largest integer that cannot be formed from non-negative multiples of the denominations). The problem asks for the minimumNwhere every integer>= Nis achievable, which is79 + 1 = 80. - Off-by-one when computing the start of the streak: When
consecutive_runreaches5atcurrent_value = 84, the five numbers are80, 81, 82, 83, 84, so the first element is84 - 5 + 1 = 80, not84 - 5 = 79. - Stopping after fewer than
min(a, b)consecutive hits: Seeing4achievable numbers in a row (75, 76, 77, 78) is not enough — adding5jumps from75..78to80..83, skipping right over79! - Applying
a * b - a - b + 1without checkinggcd(a, b) == 1anda, b >= 2: Plugging(4, 6)into the formula outputs15even though15is odd and impossible, and plugging(1, 5)outputs0instead of the smallest positive integer1.
Alternative approaches
- Closed-form Chicken McNugget theorem: For coprime integers
a, b >= 2, returna * b - a - b + 1directly (5 * 21 - 5 - 21 + 1 = 80) inO(1)time andO(1)space. Pairing this formula with the modular-remainder proof or the DP scan demonstrates both number-theory fluency and coding rigor. - Remainder-lane computation (
O(min(a, b))): Track the smallest achievable value for each remainder modulomin(a, b)by stepping through0, b, 2 * b, ..., (a - 1) * b; the largest of those starting values minusa, plus1, givesNin just5steps.
Follow-up questions
- What closed-form expression gives the threshold N for any two coprime positive integers a and b (both at least 2), and why does it work? When
a, b >= 2satisfygcd(a, b) = 1, the largest unreachable integer isa * b - a - b, so the threshold isN = a * b - a - b + 1. Partitioning integers by their remainder moduloa(the leftover after dividing bya), the multiples0, b, 2 * b, ..., (a - 1) * bvisit alladistinct remainder lanes becauseaandbshare no common factor, andr * bis the minimum achievable total in its lane. The last lane to activate starts at(a - 1) * b, making(a - 1) * b - a = a * b - a - bthe final unreachable integer. - How many positive integers in total fail to have a valid non-negative representation 5a + 21b? For any coprime
a, b >= 1, exactly(a - 1) * (b - 1) / 2positive integers are unreachable — for5and21, that is4 * 20 / 2 = 40unreachable integers out of1..79(leaving39achievable ones below80). In each remainder lane seeded atr * b(1 <= r <= a - 1), the positive integers strictly belowr * bsharing that remainder arer * b - a, r * b - 2 * a, ..., givingr * b // amissing values per lane whose sum acrossr = 1 .. a - 1simplifies to(a - 1) * (b - 1) / 2. - How would you compute the threshold N algorithmically when three or more positive denominations are available? No simple closed-form formula exists for three or more denominations, so we generalize the remainder-lane method using Dijkstra's shortest-path algorithm (a graph search that repeatedly settles the minimum-cost reachable state first). Let
mbe the smallest denomination (say6for[6, 9, 20]): createmremainder states0 .. m - 1, initializedist[0] = 0, and from remainderrtransition along each denominationcto(r + c) % mwith candidate totaldist[r] + c. Provided thegcdof all denominations is1, every remainder becomes reachable, andmax(dist) - m + 1givesN(49 - 6 + 1 = 44for[6, 9, 20]).
Follow-up questions
- What closed-form expression gives the threshold N for any two coprime positive integers a and b (both at least 2), and why does it work?
- How many positive integers in total fail to have a valid non-negative representation 5a + 21b?
- How would you compute the threshold N algorithmically when three or more positive denominations are available?
Similar questions
- Probability the Final Passenger Gets Their Seat
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One