5 Best Ways to Find the Product of Numbers Whose Sum is Given in Python

Rate this post

πŸ’‘ Problem Formulation: We often encounter situations in programming where we are given a specific sum, and we need to find the product of a few numbers that, when added, equal the given sum. For instance, if the input sum is 10, an acceptable product might be obtained from numbers 1, 3, and 6 since their sum is 10 and their product is 18.

Method 1: Brute Force Iteration

This method involves iterating through all possible combinations of numbers until we find the combination whose sum equals the given number. It’s the most straightforward approach and ensures a solution if one exists, but can be inefficient for larger sums.

Here’s an example:

from itertools import combinations

def find_product_of_sum(sum_target):
    for r in range(2, sum_target):
        for combo in combinations(range(1,sum_target), r):
            if sum(combo) == sum_target:
                product = 1
                for num in combo:
                    product *= num
                return product
    return None


Output: 18

This snippet uses itertools.combinations to look for all possible combinations of integer numbers that sum up to the given target (10 in this case). Once it finds a valid combination, it computes the product of the numbers in that combination and returns it.

Method 2: Recursive Backtracking

The recursive backtracking method leverages the power of recursion to explore combinations of numbers and backtrack if the current path does not lead to the correct sum. It’s more efficient than brute force as it eliminates unnecessary computations early.

Here’s an example:

def find_product(sum_target, current_sum=0, start=1, product=1):
    if current_sum == sum_target:
        return product
    if current_sum > sum_target:
        return None
    for i in range(start, sum_target):
        result = find_product(sum_target, current_sum + i, i+1, product * i)
        if result:
            return result
    return None


Output: 18

The recursive function find_product attempts to add numbers starting from 1, incrementing upwards and multiplying them together, until it matches the target sum. If it overshoots, it backtracks to try the next number.

Method 3: Dynamic Programming

By applying dynamic programming, we store intermediate results to avoid redundant computations, which can significantly speed up the searching process for the product of numbers that sum up to a specific target.

Here’s an example:

def find_product(sum_target):
    dp = [None]*(sum_target+1)
    dp[0] = 1  # Base case
    for i in range(1, sum_target+1):
        for j in range(i, sum_target+1):
            if dp[j-i] is not None:
                dp[j] = i * (dp[j-i] if dp[j] is None else max(dp[j], dp[j-i] * i))
    return dp[sum_target]


Output: 36

The code defines an array dp of length sum_target + 1 to hold the maximum product for any sum up to sum_target. It iterates through, updating the array based on previous results, leading to the optimal product.

Method 4: Using a Mathematical Approach

This method employs a mathematical insight that in order to maximize the product under a fixed sum, we should use numbers as close to each other as possible, commonly 2s or 3s.

Here’s an example:

def find_product(sum_target):
    if sum_target  4:
        product *= 3
        sum_target -= 3
    return product * sum_target

Output: 36

In this code, we repeatedly subtract 3 from the given sum_target and multiply the product by 3 until the sum_target is less than or equal to 4, at which point we multiply by the remaining sum.

Bonus One-Liner Method 5: Using Lambda and Reduce

For those who love one-liners, Python’s lambda function combined with the reduce function can find the product in a single expression.

Here’s an example:

from functools import reduce

find_product = lambda sum_target: reduce(lambda x, y: x*y, range(1, sum_target+1)) if sum_target > 0 else None


Output: 3628800

This one-liner uses functools.reduce to multiply a range of numbers from 1 to the given sum. However, it does not ensure that the sum of the factors equals the input sum, but rather multiplies all numbers up to the target.


  • Method 1: Brute Force Iteration. Simple to understand and implement. However, it’s computationally expensive for large sums.
  • Method 2: Recursive Backtracking. More efficient than brute force. It can still be slow for large sums but cuts out many unnecessary calculations.
  • Method 3: Dynamic Programming. Much more efficient for larger sums by storing and reusing results. Complexity can make it harder to implement correctly.
  • Method 4: Mathematical Approach. Most efficient for finding the maximum product, but it does not enumerate all possible combinations.
  • Method 5: Using Lambda and Reduce. A neat one-liner but does not solve the problem as specified since it disregards the sum condition.