Find smallest N for 5-and-21 sums
Company: Schonfeld
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates understanding of integer linear combinations and elementary number theory, framed as a Frobenius coin problem that examines representability using non-negative multiples of 5 and 21.
Constraints
- 1 <= p, q <= 10000
- p and q are positive integers
- Return -1 when gcd(p, q) > 1 (no finite N exists)
- Return 0 when either p or q equals 1
Examples
Input: (5, 21)
Expected Output: 80
Explanation: The original interview instance. Coprime, so N = 5*21 - 5 - 21 + 1 = 80; 79 is the largest value that cannot be written as 5a + 21b.
Input: (3, 5)
Expected Output: 8
Explanation: Largest non-representable value is 3*5 - 3 - 5 = 7 (you cannot make 7 from 3s and 5s), so every integer >= 8 is representable.
Input: (2, 3)
Expected Output: 2
Explanation: Largest non-representable value is 2*3 - 2 - 3 = 1, so every integer >= 2 is representable.
Input: (4, 6)
Expected Output: -1
Explanation: gcd(4,6)=2, so only even numbers are ever representable; no finite N can cover all integers above it.
Input: (1, 7)
Expected Output: 0
Explanation: With a denomination of 1, every non-negative integer is representable, so N = 0.
Input: (7, 11)
Expected Output: 60
Explanation: Coprime, so N = 7*11 - 7 - 11 + 1 = 60; the largest non-representable value is 59.
Input: (5, 5)
Expected Output: -1
Explanation: gcd(5,5)=5, only multiples of 5 are representable, so no finite N exists — edge case with equal denominations sharing a factor.
Hints
- This is the Frobenius (Chicken McNugget) problem. The answer N is one more than the largest integer that CANNOT be written as p*a + q*b.
- If p and q share a common factor > 1, only multiples of that factor are representable, so no finite N exists — handle that case separately.
- For coprime p and q there is a closed form: the largest non-representable integer is p*q - p - q, so N = p*q - p - q + 1. You can also compute it with a DP reachability scan up to p*q.
- A simple verification: build a boolean array `reachable[0..p*q]`, mark reachable[x] true if reachable[x-p] or reachable[x-q] is true, then N is the index after the last false.