Breaking an Integer to get Maximum Product
Last Updated :
10 Apr, 2024
Given a number n, the task is to break n in such a way that multiplication of its parts is maximized.
Input : n = 10
Output: 36
Explanation: 10 = 4 + 3 + 3 and 4 * 3 * 3 = 36 is the maximum possible product.
Input: n = 8
Output: 18
Explanation: 8 = 2 + 3 + 3 and 2 * 3 * 3 = 18 is the maximum possible product.
Mathematically, we are given n and we need to maximize a1 * a2 * a3 …. * aK such that n = a1 + a2 + a3 … + aK and a1, a2, ... ak > 0.
Note that we need to break given Integer in at least two parts in this problem for maximizing the product.
Method 1 -
Now we know from maxima-minima concept that, If an integer need to break in two parts, then to maximize their product those part should be equal. Using this concept lets break n into (n/x) x's then their product will be x(n/x), now if we take derivative of this product and make that equal to 0 for maxima, we will get to know that value of x should be e (base of the natural logarithm) for maximum product. As we know that 2 < e < 3, so we should break every Integer into 2 or 3 only for maximum product.
Next thing is 6 = 3 + 3 = 2 + 2 + 2, but 3 * 3 > 2 * 2 * 2, that is every triplet of 2 can be replaced with tuple of 3 for maximum product, so we will keep breaking the number in terms of 3 only, until number remains as 4 or 2, which we will be broken into 2*2 (2*2 > 3*1) and 2 respectively and we will get our maximum product.
In short, procedure to get maximum product is as follows – Try to break integer in power of 3 only and when integer remains small (<5) then use brute force.
The complexity of below program is O(log N), because of repeated squaring power method.
Follow the below steps to implement the above idea:
- Define a function breakInteger that takes an integer N as input and returns the maximum product that can be obtained by breaking N into a sum of positive integers.
- Check for the two base cases:
- If N is 2, return 1.
- If N is 3, return 2.
- Define a variable maxProduct to store the maximum product.
- Determine the remainder of N when divided by 3:
a. If the remainder is 0, the maximum product is 3 raised to the power of N/3.
b. If the remainder is 1, the maximum product is 2 multiplied by 2 multiplied by 3 raised to the power of (N/3)-1.
c. If the remainder is 2, the maximum product is 2 multiplied by 3 raised to the power of N/3. - Return the value of maxProduct.
Below is the implementation of the above approach:
C++
// C/C++ program to find maximum product by breaking
// the Integer
#include <bits/stdc++.h>
using namespace std;
// method return x^a in log(a) time
int power(int x, int a)
{
int res = 1;
while (a) {
if (a & 1)
res = res * x;
x = x * x;
a >>= 1;
}
return res;
}
// Method returns maximum product obtained by
// breaking N
int breakInteger(int N)
{
// base case 2 = 1 + 1
if (N == 2)
return 1;
// base case 3 = 2 + 1
if (N == 3)
return 2;
int maxProduct;
// breaking based on mod with 3
switch (N % 3) {
// If divides evenly, then break into all 3
case 0:
maxProduct = power(3, N / 3);
break;
// If division gives mod as 1, then break as
// 4 + power of 3 for remaining part
case 1:
maxProduct = 2 * 2 * power(3, (N / 3) - 1);
break;
// If division gives mod as 2, then break as
// 2 + power of 3 for remaining part
case 2:
maxProduct = 2 * power(3, N / 3);
break;
}
return maxProduct;
}
// Driver code to test above methods
int main()
{
int maxProduct = breakInteger(10);
cout << maxProduct << endl;
return 0;
}
Java
// Java program to find maximum product by breaking
// the Integer
class GFG {
// method return x^a in log(a) time
static int power(int x, int a)
{
int res = 1;
while (a > 0) {
if ((a & 1) > 0)
res = res * x;
x = x * x;
a >>= 1;
}
return res;
}
// Method returns maximum product obtained by
// breaking N
static int breakInteger(int N)
{
// base case 2 = 1 + 1
if (N == 2)
return 1;
// base case 3 = 2 + 1
if (N == 3)
return 2;
int maxProduct = -1;
// breaking based on mod with 3
switch (N % 3) {
// If divides evenly, then break into all 3
case 0:
maxProduct = power(3, N / 3);
break;
// If division gives mod as 1, then break as
// 4 + power of 3 for remaining part
case 1:
maxProduct = 2 * 2 * power(3, (N / 3) - 1);
break;
// If division gives mod as 2, then break as
// 2 + power of 3 for remaining part
case 2:
maxProduct = 2 * power(3, N / 3);
break;
}
return maxProduct;
}
// Driver code to test above methods
public static void main(String[] args)
{
int maxProduct = breakInteger(10);
System.out.println(maxProduct);
}
}
// This code is contributed by mits
Python3
# Python3 program to find maximum product by breaking
# the Integer
# method return x^a in log(a) time
def power(x, a):
res = 1
while (a):
if (a & 1):
res = res * x
x = x * x
a >>= 1
return res
# Method returns maximum product obtained by
# breaking N
def breakInteger(N):
# base case 2 = 1 + 1
if (N == 2):
return 1
# base case 3 = 2 + 1
if (N == 3):
return 2
maxProduct = 0
# breaking based on mod with 3
if(N % 3 == 0):
# If divides evenly, then break into all 3
maxProduct = power(3, int(N/3))
return maxProduct
elif(N % 3 == 1):
# If division gives mod as 1, then break as
# 4 + power of 3 for remaining part
maxProduct = 2 * 2 * power(3, int(N/3) - 1)
return maxProduct
elif(N % 3 == 2):
# If division gives mod as 2, then break as
# 2 + power of 3 for remaining part
maxProduct = 2 * power(3, int(N/3))
return maxProduct
# Driver code to test above methods
maxProduct = breakInteger(10)
print(maxProduct)
# This code is contributed by mits
C#
// C# program to find maximum product by breaking
// the Integer
class GFG {
// method return x^a in log(a) time
static int power(int x, int a)
{
int res = 1;
while (a > 0) {
if ((a & 1) > 0)
res = res * x;
x = x * x;
a >>= 1;
}
return res;
}
// Method returns maximum product obtained by
// breaking N
static int breakInteger(int N)
{
// base case 2 = 1 + 1
if (N == 2)
return 1;
// base case 3 = 2 + 1
if (N == 3)
return 2;
int maxProduct = -1;
// breaking based on mod with 3
switch (N % 3) {
// If divides evenly, then break into all 3
case 0:
maxProduct = power(3, N / 3);
break;
// If division gives mod as 1, then break as
// 4 + power of 3 for remaining part
case 1:
maxProduct = 2 * 2 * power(3, (N / 3) - 1);
break;
// If division gives mod as 2, then break as
// 2 + power of 3 for remaining part
case 2:
maxProduct = 2 * power(3, N / 3);
break;
}
return maxProduct;
}
// Driver code to test above methods
public static void Main()
{
int maxProduct = breakInteger(10);
System.Console.WriteLine(maxProduct);
}
}
// This code is contributed by mits
JavaScript
<script>
// Javascript program to find maximum
// product by breaking the Integer
// Method return x^a in log(a) time
function power(x, a)
{
let res = 1;
while (a > 0)
{
if ((a & 1) > 0)
res = res * x;
x = x * x;
a >>= 1;
}
return res;
}
// Method returns maximum product obtained by
// breaking N
function breakInteger(N)
{
// Base case 2 = 1 + 1
if (N == 2)
return 1;
// Base case 3 = 2 + 1
if (N == 3)
return 2;
let maxProduct;
// Breaking based on mod with 3
switch (N % 3)
{
// If divides evenly, then break into all 3
case 0:
maxProduct = power(3, N / 3);
break;
// If division gives mod as 1, then break as
// 4 + power of 3 for remaining part
case 1:
maxProduct = 2 * 2 * power(3, (N / 3) - 1);
break;
// If division gives mod as 2, then break as
// 2 + power of 3 for remaining part
case 2:
maxProduct = 2 * power(3, N / 3);
break;
}
return maxProduct;
}
// Driver code
let maxProduct = breakInteger(10);
document.write(maxProduct);
// This code is contributed by rameshtravel07
</script>
PHP
<?php
// PHP program to find maximum product by breaking
// the Integer
// method return x^a in log(a) time
function power($x, $a)
{
$res = 1;
while ($a)
{
if ($a & 1)
$res = $res * $x;
$x = $x * $x;
$a >>= 1;
}
return $res;
}
// Method returns maximum product obtained by
// breaking N
function breakInteger($N)
{
// base case 2 = 1 + 1
if ($N == 2)
return 1;
// base case 3 = 2 + 1
if ($N == 3)
return 2;
$maxProduct=0;
// breaking based on mod with 3
switch ($N % 3)
{
// If divides evenly, then break into all 3
case 0:
$maxProduct = power(3, $N/3);
break;
// If division gives mod as 1, then break as
// 4 + power of 3 for remaining part
case 1:
$maxProduct = 2 * 2 * power(3, ($N/3) - 1);
break;
// If division gives mod as 2, then break as
// 2 + power of 3 for remaining part
case 2:
$maxProduct = 2 * power(3, $N/3);
break;
}
return $maxProduct;
}
// Driver code to test above methods
$maxProduct = breakInteger(10);
echo $maxProduct;
// This code is contributed by mits
?>
Method 2 -
If we see some examples of this problems, we can easily observe following pattern.
The maximum product can be obtained be repeatedly cutting parts of size 3 while size is greater than 4, keeping the last part as size of 2 or 3 or 4. For example, n = 10, the maximum product is obtained by 3, 3, 4. For n = 11, the maximum product is obtained by 3, 3, 3, 2. Following is the implementation of this approach.
C++
#include <iostream>
using namespace std;
/* The main function that returns the max possible product */
int maxProd(int n)
{
// n equals to 2 or 3 must be handled explicitly
if (n == 2 || n == 3) return (n-1);
// Keep removing parts of size 3 while n is greater than 4
int res = 1;
while (n > 4)
{
n -= 3;
res *= 3; // Keep multiplying 3 to res
}
return (n * res); // The last part multiplied by previous parts
}
/* Driver program to test above functions */
int main()
{
cout << "Maximum Product is " << maxProd(45);
return 0;
}
Java
public class GFG
{
/* The main function that returns the max possible product */
static int maxProd(int n)
{
// n equals to 2 or 3 must be handled explicitly
if (n == 2 || n == 3) return (n - 1);
// Keep removing parts of size 3 while n is greater than 4
int res = 1;
while (n > 4)
{
n -= 3;
res *= 3; // Keep multiplying 3 to res
}
return (n * res); // The last part multiplied by previous parts
}
// Driver code
public static void main(String[] args) {
System.out.println("Maximum Product is " + maxProd(45));
}
}
// This code is contributed by divyeshrabadiya07
Python3
''' The main function that returns the max possible product '''
def maxProd(n):
# n equals to 2 or 3 must be handled explicitly
if (n == 2 or n == 3):
return (n - 1)
# Keep removing parts of size 3 while n is greater than 4
res = 1
while (n > 4):
n -= 3
res *= 3 # Keep multiplying 3 to res
return (n * res) # The last part multiplied by previous parts
''' Driver program to test above functions '''
if __name__ == '__main__':
print("Maximum Product is", maxProd(45))
# This code is contributed by rutvik_56.
C#
using System;
class GFG {
/* The main function that returns the max possible product */
static int maxProd(int n)
{
// n equals to 2 or 3 must be handled explicitly
if (n == 2 || n == 3) return (n - 1);
// Keep removing parts of size 3 while n is greater than 4
int res = 1;
while (n > 4)
{
n -= 3;
res *= 3; // Keep multiplying 3 to res
}
return (n * res); // The last part multiplied by previous parts
}
// Driver code
static void Main()
{
Console.WriteLine("Maximum Product is " + maxProd(45));
}
}
// This code is contributed by divyesh072019.
JavaScript
<script>
/* The main function that returns the max possible product */
function maxProd(n)
{
// n equals to 2 or 3 must be handled explicitly
if (n == 2 || n == 3) return (n - 1);
// Keep removing parts of size 3 while n is greater than 4
let res = 1;
while (n > 4)
{
n -= 3;
res *= 3; // Keep multiplying 3 to res
}
return (n * res); // The last part multiplied by previous parts
}
document.write("Maximum Product is " + maxProd(45));
</script>
OutputMaximum Product is 14348907
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 3: (Using Recursion)
Intuition:
Basically in this problem, We have to maximize the product of some integers which sums up to the given integer. Let's take an example of n = 5 and try to solve it. So, we can break 5 to 4,1 or 3,1,1 or 2,1,1,1 or 1,1,1,1,1. We can also break it instead to 3,2 or 1,2,2 or 1,1,1,2 and so on.After taking all these possibilities, [3,2] gives the max product which is 6. Basically we see that our problem is getting divided into subproblems. Thus we can make use of recursion to solve this. Further, if we want to solve for n = 6, we can make use of the previous max product value we got for n = 5 that is 6 to check possibilites for 6, so we can easily do memoization in our recursive solution to reduce our time complexity.
Approach:
The idea is that at every value, we can loop from 1 to n-1 for the first value (a). The remain value (b) has two options:
Keep the same, which means the product will be a * b
Or broken down, which means the product is: a * max(integerBreak(b))
C++
#include <iostream>
using namespace std;
/* The main function that returns the max possible product */
int helper(int n, int idx)
{
//base condition
if(n == 0 or idx == 0) return 1;
//recursive call for each step
if(idx > n) return helper(n, idx - 1);
//return the maximum result obtained from recursive calls
return max((idx * helper(n - idx, idx)), helper(n , idx - 1));
}
//max product function
int maxProd(int n)
{
return helper(n, n - 1);
}
/* Driver program to test above functions */
int main()
{
cout << "Maximum Product is " << maxProd(45);
return 0;
}
Java
public class GFG {
/* The main function that returns the max possible product */
static int helper(int n, int idx) {
// base condition
if (n == 0 || idx == 0)
return 1;
// recursive call for each step
if (idx > n)
return helper(n, idx - 1);
// return the maximum result obtained from recursive calls
return Math.max((idx * helper(n - idx, idx)), helper(n, idx - 1));
}
// max product function
static int maxProd(int n) {
return helper(n, n - 1);
}
/* Driver program to test above functions */
public static void main(String[] args) {
System.out.println("Maximum Product is " + maxProd(45));
}
}
Python3
# Python code for the above approach
# The main function that returns the max possible product
def helper(n, idx):
# Base condition
if n == 0 or idx == 0:
return 1
# Recursive call for each step
if idx > n:
return helper(n, idx - 1)
# Return the maximum result obtained from recursive calls
return max((idx * helper(n - idx, idx)), helper(n, idx - 1))
# Max product function
def maxProd(n):
return helper(n, n - 1)
# Driver program to test above functions
if __name__ == "__main__":
print("Maximum Product is", maxProd(45))
# This code is contributed by Susobhan Akhuli
C#
// C# code for the above approach
using System;
public class GFG {
/* The main function that returns the max possible
* product */
static int Helper(int n, int idx)
{
// base condition
if (n == 0 || idx == 0)
return 1;
// recursive call for each step
if (idx > n)
return Helper(n, idx - 1);
// return the maximum result obtained from recursive
// calls
return Math.Max((idx * Helper(n - idx, idx)),
Helper(n, idx - 1));
}
// max product function
static int MaxProd(int n) { return Helper(n, n - 1); }
/* Driver program to test above functions */
public static void Main(string[] args)
{
Console.WriteLine("Maximum Product is "
+ MaxProd(45));
}
}
// This code is contributed by Susobhan Akhuli
JavaScript
// function to calculate the max product
function helper(n, idx) {
// If n or idx is 0, return 1
if (n === 0 || idx === 0) return 1;
// If idx is > n, recursive call with a smaller idx
if (idx > n) return helper(n, idx - 1);
//return the maximum result obtained from recursive calls
return Math.max(idx * helper(n - idx, idx), helper(n, idx - 1));
}
//max product function
function maxProd(n) {
return helper(n, n - 1);
}
// Driver code
console.log("Maximum Product is " + maxProd(45));
OutputMaximum Product is 14348907
Time Complexity: O(n),fo making the recursive calls.
Auxiliary Space: O(n), recursive stack space
Similar Reads
Introduction to Knapsack Problem, its Types and How to solve them
The Knapsack problem is an example of the combinational optimization problem. This problem is also commonly known as the "Rucksack Problem". The name of the problem is defined from the maximization problem as mentioned below:Given a bag with maximum weight capacity of W and a set of items, each havi
6 min read
0/1 Knapsack
0/1 Knapsack Problem
Given n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. Note: The constraint
15+ min read
Printing Items in 0/1 Knapsack
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays, val[0..n-1] and wt[0..n-1] represent values and weights associated with n items respectively. Also given an integer W which repre
12 min read
0/1 Knapsack Problem to print all possible solutions
Given weights and profits of N items, put these items in a knapsack of capacity W. The task is to print all possible solutions to the problem in such a way that there are no remaining items left whose weight is less than the remaining capacity of the knapsack. Also, compute the maximum profit.Exampl
10 min read
0-1 knapsack queries
Given an integer array W[] consisting of weights of the items and some queries consisting of capacity C of knapsack, for each query find maximum weight we can put in the knapsack. Value of C doesn't exceed a certain integer C_MAX. Examples: Input: W[] = {3, 8, 9} q = {11, 10, 4} Output: 11 9 3 If C
12 min read
0/1 Knapsack using Branch and Bound
Given two arrays v[] and w[] that represent values and weights associated with n items respectively. Find out the maximum value subset(Maximum Profit) of v[] such that the sum of the weights of this subset is smaller than or equal to Knapsack capacity W.Note: The constraint here is we can either put
15+ min read
0/1 Knapsack using Least Cost Branch and Bound
Given N items with weights W[0..n-1], values V[0..n-1] and a knapsack with capacity C, select the items such that:Â Â The sum of weights taken into the knapsack is less than or equal to C.The sum of values of the items in the knapsack is maximum among all the possible combinations.Examples:Â Â Input:
15+ min read
Unbounded Fractional Knapsack
Given the weights and values of n items, the task is to put these items in a knapsack of capacity W to get the maximum total value in the knapsack, we can repeatedly put the same item and we can also put a fraction of an item. Examples: Input: val[] = {14, 27, 44, 19}, wt[] = {6, 7, 9, 8}, W = 50 Ou
5 min read
Unbounded Knapsack (Repetition of items allowed)
Given a knapsack weight, say capacity and a set of n items with certain value vali and weight wti, The task is to fill the knapsack in such a way that we can get the maximum profit. This is different from the classical Knapsack problem, here we are allowed to use an unlimited number of instances of
15+ min read
Unbounded Knapsack (Repetition of items allowed) | Efficient Approach
Given an integer W, arrays val[] and wt[], where val[i] and wt[i] are the values and weights of the ith item, the task is to calculate the maximum value that can be obtained using weights not exceeding W. Note: Each weight can be included multiple times. Examples: Input: W = 4, val[] = {6, 18}, wt[]
8 min read
Double Knapsack | Dynamic Programming
Given an array arr[] containing the weight of 'n' distinct items, and two knapsacks that can withstand capactiy1 and capacity2 weights, the task is to find the sum of the largest subset of the array 'arr', that can be fit in the two knapsacks. It's not allowed to break any items in two, i.e. an item
15+ min read
Some Problems of Knapsack problem
Partition a Set into Two Subsets of Equal Sum
Given an array arr[], the task is to check if it can be partitioned into two parts such that the sum of elements in both parts is the same.Note: Each element is present in either the first subset or the second subset, but not in both.Examples: Input: arr[] = [1, 5, 11, 5]Output: true Explanation: Th
15+ min read
Count of subsets with sum equal to target
Given an array arr[] of length n and an integer target, the task is to find the number of subsets with a sum equal to target.Examples: Input: arr[] = [1, 2, 3, 3], target = 6 Output: 3 Explanation: All the possible subsets are [1, 2, 3], [1, 2, 3] and [3, 3]Input: arr[] = [1, 1, 1, 1], target = 1 Ou
15+ min read
Length of longest subset consisting of A 0s and B 1s from an array of strings
Given an array arr[] consisting of binary strings, and two integers a and b, the task is to find the length of the longest subset consisting of at most a 0s and b 1s.Examples:Input: arr[] = ["1" ,"0" ,"0001" ,"10" ,"111001"], a = 5, b = 3Output: 4Explanation: One possible way is to select the subset
15+ min read
Breaking an Integer to get Maximum Product
Given a number n, the task is to break n in such a way that multiplication of its parts is maximized. Input : n = 10Output: 36Explanation: 10 = 4 + 3 + 3 and 4 * 3 * 3 = 36 is the maximum possible product. Input: n = 8Output: 18Explanation: 8 = 2 + 3 + 3 and 2 * 3 * 3 = 18 is the maximum possible pr
15+ min read
Coin Change - Minimum Coins to Make Sum
Given an array of coins[] of size n and a target value sum, where coins[i] represent the coins of different denominations. You have an infinite supply of each of the coins. The task is to find the minimum number of coins required to make the given value sum. If it is not possible to form the sum usi
15+ min read
Coin Change - Count Ways to Make Sum
Given an integer array of coins[] of size n representing different types of denominations and an integer sum, the task is to count all combinations of coins to make a given value sum. Note: Assume that you have an infinite supply of each type of coin. Examples: Input: sum = 4, coins[] = [1, 2, 3]Out
15+ min read
Maximum sum of values of N items in 0-1 Knapsack by reducing weight of at most K items in half
Given weights and values of N items and the capacity W of the knapsack. Also given that the weight of at most K items can be changed to half of its original weight. The task is to find the maximum sum of values of N items that can be obtained such that the sum of weights of items in knapsack does no
15+ min read