Skip to main content

Minimum Number of Primes to Sum to Target - Solution & Explanation

MediumPremiumFree on FleetCodeArrayMathDynamic ProgrammingNumber Theory9 min readAsked at: Amazon
Practice this problem

Problem Statement

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.

Example 3:

Input: n = 7, m = 6

Output: 1

Explanation:

The first 6 primes are [2, 3, 5, 7, 11, 13]. The sum 7 can be formed directly by prime 7, requiring only 1 prime.

 

Constraints:

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

Approach Overview

Problem Overview: You are given a target integer and need to determine the minimum number of prime numbers whose sum equals that target. Each prime can be used multiple times, and the goal is to minimize the count of primes used to reach the exact sum.

Approach 1: Brute Force Enumeration (Exponential Time, O(2^n) time, O(n) space)

The most direct idea is to try every combination of prime numbers that could sum to the target. First generate all primes up to the target using a simple primality test. Then recursively explore combinations where you add a prime and reduce the remaining target. Track the minimum number of primes used whenever the remaining value reaches zero. This approach behaves like exhaustive search and quickly becomes infeasible as the target grows because the recursion tree expands exponentially. It is useful conceptually because it reveals that the problem behaves like an unbounded combination problem similar to coin change.

Approach 2: Preprocessing + Dynamic Programming (O(n^2 / log n) time, O(n) space)

A practical solution treats each prime as a "coin" and the target as the amount to construct. Start by generating all prime numbers up to the target using the Sieve of Eratosthenes, a classic technique from number theory. This preprocessing step runs in roughly O(n log log n) time and produces the list of usable primes.

Next apply a bottom‑up dynamic programming strategy similar to the unbounded coin change problem. Create an array dp[i] representing the minimum number of primes required to form sum i. Initialize dp[0] = 0 and all other values to infinity. For every prime p, iterate through sums from p to the target and update dp[i] = min(dp[i], dp[i - p] + 1). Each update represents using prime p as the last element in the sum.

This method systematically builds answers for all smaller sums before computing the final target. The DP array ensures each state is computed once, turning the exponential brute force search into a polynomial-time solution. The algorithm mainly performs array updates and prime iterations, making it efficient even for relatively large targets. The logic relies heavily on patterns from dynamic programming and simple iteration over an array state table.

Recommended for interviews: The sieve + dynamic programming approach is what interviewers expect. Explaining the brute force recursion first demonstrates that you understand the combinational nature of the problem. Converting it into a coin-change style DP with precomputed primes shows the optimization step that interviewers look for. It also clearly communicates your understanding of state transitions and preprocessing techniques.

Solution

We can first preprocess to obtain the first 1000 prime numbers, and then use dynamic programming to solve the problem.

Define f[i] as the minimum number of primes needed to sum up to i. Initially, set f[0] = 0 and all other f[i] = infty. For each prime p, we can update f[i] from f[i - p] as follows:

$ f[i] = min(f[i], f[i - p] + 1)

If f[n] is still infty, it means it is impossible to obtain n as the sum of the first m primes, so return -1; otherwise, return f[n].

The time complexity is O(m times n), and the space complexity is O(n + M), where M is the number of preprocessed primes (here it is 1000$).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force EnumerationO(2^n)O(n)Understanding the search space or validating small inputs
Sieve Preprocessing + Dynamic ProgrammingO(n^2 / log n)O(n)General solution for large targets where optimal performance is required

Video Solution

Minimum Number of Primes to Sum to Target • Owen Wu • 118 views views

Frequently Asked Questions

Is Minimum Number of Primes to Sum to Target easy or hard?
The problem is generally classified as Medium difficulty. The challenge is recognizing that it behaves like the unbounded coin change problem but with primes as the available values. Once that connection is made, the dynamic programming transition becomes straightforward.
Minimum Number of Primes to Sum to Target Python/Java solution
Implementations typically start with a sieve to build the list of primes up to the target. Then a dynamic programming array updates dp[i] = min(dp[i], dp[i - p] + 1) for each prime p. The same logic translates cleanly across Python, Java, C++, Go, and TypeScript.
How to solve Minimum Number of Primes to Sum to Target in O(n)?
A strict O(n) solution generally is not achievable because multiple primes must be evaluated for every intermediate sum. The standard optimized approach uses a sieve to generate primes and dynamic programming to compute the minimum counts. This results in roughly O(n^2 / log n) time while keeping space complexity linear.
What is the best approach for Minimum Number of Primes to Sum to Target?
The most effective method combines prime preprocessing with dynamic programming. First generate all primes up to the target using the Sieve of Eratosthenes, then apply a coin-change style DP where dp[i] stores the minimum number of primes required to form sum i. This approach avoids exponential search and runs in roughly O(n^2 / log n) time with O(n) space.
Is Minimum Number of Primes to Sum to Target asked at Google/Amazon/Meta?
Problems combining primes with dynamic programming appear frequently in interviews at large tech companies. Variants of coin change, prime decomposition, and number theory DP problems have been reported in interviews at companies like Google and Amazon because they test algorithm design and preprocessing techniques.
What data structure is used in Minimum Number of Primes to Sum to Target?
The core data structure is a one-dimensional dynamic programming array where dp[i] stores the minimum number of primes needed to reach sum i. A boolean array is also commonly used during the Sieve of Eratosthenes to mark prime numbers during preprocessing.
What is the time complexity of Minimum Number of Primes to Sum to Target?
The optimal solution runs in about O(n^2 / log n) time. The sieve step takes O(n log log n) to generate primes, and the dynamic programming step iterates through each prime and updates states up to the target. Space complexity is O(n) for the DP array.

Ready to solve this problem?

Practice Minimum Number of Primes to Sum to Target with our built-in code editor and test cases.

Practice on FleetCode