Problem
You are given two distinct prime numbers primeOne
and primeTwo
.
Alice and Bob are visiting a market. The market has an infinite number of items, for any positive integer x
there exists an item whose price is
x
. Alice wants to buy some items from the market to gift to Bob. She has an
infinite number of coins in the denomination primeOne
and primeTwo
.
She wants to know the most expensive item she can not buy to gift to Bob.
Return the price of themost expensive item which Alice can not gift to Bob.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 < primeOne, primeTwo < 10^4
primeOne
,primeTwo
are prime numbers.primeOne * primeTwo < 10^5
Solution
Method 1 - Number Theory (Frobenius Number)
Intuition
This is a classic coin problem: with two coprime denominations (distinct primes), the largest number that cannot be formed is primeOne * primeTwo - primeOne - primeTwo (Frobenius number). All numbers greater than this can be formed.
Approach
Return primeOne * primeTwo - primeOne - primeTwo.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
— Direct formula. - 🧺 Space complexity:
O(1)
— No extra space used.