510. Minimum Primes

You are given two integers n and m.

You have to select a multiset of prime numbers from the first m prime numbers such that the sum of the selected primes is exactly n. You may use each prime number multiple times.

Return the minimum number of prime numbers needed to sum up to n, or -1 if it is not possible.

Example 1:

Input: n = 10, m = 2

Output: 4

Explanation:

The first 2 primes are [2, 3]. The sum 10 can be formed as 2 + 2 + 3 + 3, requiring 4 primes.

Example 2:

Input: n = 15, m = 5

Output: 3

Explanation:

The first 5 primes are [2, 3, 5, 7, 11]. The sum 15 can be formed as 5 + 5 + 5, requiring 3 primes.

Now Your Turn!

Pick the correct output for the given input

Input: n = 7, m = 4

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n <= 1000
  • 1 <= m <= 1000

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int minNumberOfPrimes(int n, int m) {
//Enter your code here. Best of luck!
}
};
Test Case

Input:

Input
M
N