Maximize the product of four factors of a Number

Given an integer N, the task is to find the maximum product of A, B, C, D such that below conditions satisfy:

  • N%A ==0 && N%B ==0 && N%C ==0 && N%D ==0.
  • Maximize the product A*B*C*D where N = A+B+C+D.

If no solution exists, print ‘-1’ (without quotes).

Examples:

Input: N = 8
Output: 16
The divisors of 8 are {1, 2, 4, 8}. 
The maximized product can be formed 
by multiplying 2*2*2*2 = 16 as 2+2+2+2 = 8.

Input: N = 4 
Output: 1
The divisors of 4 are {1, 2, 4}. 
The maximized product can be formed
by multiplying 1*1*1*1 = 1 as 1+1+1+1 =4.

Naive Approach:

  1. Find out the factors of the given number and store them in an vector named factors in O(sqrt(n)) complexity.
  2. Initialize product = -1 and then we iterate over the factors vector to apply the brute force method to find the maximized product.

Below is the implementation of above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
  
// Declare the vector of factors for storing the
vector<int> factors;
  
// function to find out the factors of a number
void findFactors(int n)
{
    // Loop until the i reaches the sqrt(n)
    for (int i = 1; i * i <= n; i++) {
  
        // Check if i is a factor of n
        if (n % i == 0) {
  
            // if both the factors are same
            // we only push one factor
            if ((n / i) == i)
                factors.push_back(i);
  
            else {
  
                // factor1 is pushed
                factors.push_back(n / i);
  
                // factor2 is pushed
                factors.push_back(i);
            }
        }
    }
}
  
// Function to find the maximum product
int findProduct(int n)
{
    // Initialize the product with -1
    int product = -1;
    int si = factors.size();
    for (int i = 0; i < si; i++)
        for (int j = 0; j < si; j++)
            for (int k = 0; k < si; k++)
                for (int l = 0; l < si; l++) {
  
                    // Find the sum of factors and store it in s
                    int s = factors[i] + factors[j]
                            + factors[k] + factors[l];
  
                    // Compare whether it is equal to the n
                    if (s == n) {
  
                        // product of factors
                        int p = factors[i] * factors[j] * factors[k] * factors[l];
  
                        // Check whether we have a better
                        // p now if yes update
                        if (p > product)
                            product = p;
                    }
                }
  
    return product;
}
  
// Driver code
int main()
{
    int n = 10;
  
    // initializes the vectors with the divisors of n
    findFactors(n);
  
    // prints out the maximised product.
    cout << findProduct(n);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of above approach 
  
import java.util.ArrayList;
import java.util.List;
  
public class GFG {
  
// Declare the ArrayList of factors for storing the 
    static List< Integer> factors = new ArrayList<>(10);
  
// function to find out the factors of a number 
    static void findFactors(int n) {
        // Loop until the i reaches the sqrt(n) 
        for (int i = 1; i * i <= n; i++) {
  
            // Check if i is a factor of n 
            if (n % i == 0) {
                // if both the factors are same 
                // we only push one factor 
                if ((n / i) == i) {
                    factors.add(factors.size(), i);
                } else {
  
                    // factor1 is pushed 
                    factors.add(factors.size(), n / i);
  
                    // factor2 is pushed 
                    factors.add(factors.size(), i);
                }
            }
        }
    }
  
// Function to find the maximum product 
    static int findProduct(int n) {
        // Initialize the product with -1 
  
        int product = -1;
        int si = factors.size();
        for (int i = 0; i < si; i++) {
            for (int j = 0; j < si; j++) {
                for (int k = 0; k < si; k++) {
                    for (int l = 0; l < si; l++) {
  
                        // Find the sum of factors and store it in s 
                        int s = factors.get(i) + factors.get(j)
                                + factors.get(k) + factors.get(l);
  
                        // Compare whether it is equal to the n 
                        if (s == n) {
  
                            // product of factors 
                            int p = factors.get(i) * factors.get(j) * factors.get(k) * 
                                               factors.get(l);
  
                            // Check whether we have a better 
                            // p now if yes update 
                            if (p > product) {
                                product = p;
                            }
                        }
                    }
                }
            }
        }
  
        return product;
    }
  
    // Driver Code 
    public static void main(String[] args) {
        int n = 10;
  
        // intializes the List with the divisors of n 
        findFactors(n);
        // prints out the maximised product. 
        System.out.println(findProduct(n));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 implementation of above approach
from math import sqrt
  
# Declare the vector of factors 
# for storing the
factors = []
  
# function to find out the factors 
# of a number
def findFactors(n):
      
    # Loop until the i reaches the sqrt(n)
    for i in range(1, int(sqrt(n)) + 1, 1):
          
        # Check if i is a factor of n
        if (n % i == 0):
              
            # if both the factors are same
            # we only push one factor
            if ((n / i) == i):
                factors.append(i)
  
            else:
                  
                # factor1 is pushed
                factors.append(n / i)
  
                # factor2 is pushed
                factors.append(i)
          
# Function to find the maximum product
def findProduct(n):
      
    # Initialize the product with -1
    product = -1
    si = len(factors)
    for i in range(si):
        for j in range(si):
            for k in range(si):
                for l in range(si):
                      
                    # Find the sum of factors and store it in s
                    s = (factors[i] + factors[j] + 
                         factors[k] + factors[l])
  
                    # Compare whether it is equal to the n
                    if (s == n):
                          
                        # product of factors
                        p = (factors[i] * factors[j] * 
                             factors[k] * factors[l])
  
                        # Check whether we have a better
                        # p now if yes update
                        if (p > product):
                            product = p
                      
    return product
  
# Driver code
if __name__ == '__main__':
    n = 10
  
    # initializes the vectors with
    # the divisors of n
    findFactors(n)
  
    # prints out the maximised product.
    print(int(findProduct(n)))
  
# This code is contributed by
# Sanjit_Prasad

chevron_right


Output:

20

Time Complexity: O((no. of divisors)^4))

Better Approach: Complexity can be slightly reduced by removing the 4th loop from the above-mentioned code and instead use a binary search to find the fourth factor. Since binary search only works when the list is sorted. So we need to sort the factors vector so that we can apply binary search to the problem.

Below is the implementation of above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
  
// We declare the vector of factors for storing the
vector<int> factors;
  
// function to find out the factors of a number
void findFactors(int n)
{
    // we loop until the i reaches the sqrt(n)
    for (int i = 1; i * i <= n; i++) {
  
        // we check if i is a factor of n
        if (n % i == 0) {
  
            // if both the factors are same
            // only push one factor
            if ((n / i) == i) {
                factors.push_back(i);
            }
            else {
  
                // factor1 is pushed
                factors.push_back(n / i);
  
                // factor2 is pushed
                factors.push_back(i);
            }
        }
    }
}
  
int findProduct(int n)
{
    // initialise the product with -1
    int product = -1;
    int si = factors.size();
  
    for (int i = 0; i < si; i++)
        for (int j = 0; j < si; j++)
            for (int k = 0; k < si; k++) {
  
                // we find the sum of factors
                // and store it in s
                int s = factors[i] + factors[j] + factors[k];
  
                // we check whether the fourth
                // factor exists or not
                if (binary_search(factors.begin(), factors.end(), n - s)) {
                    // product of factors
                    int p = factors[i] * factors[j] * factors[k] * (n - s);
  
                    // we check whether we have a better
                    // p now if yes update
                    if (p > product)
                        product = p;
                }
            }
  
    return product;
}
  
// Driver code
int main()
{
    int n = 10;
  
    // initializes the vectors with the divisors of n
    findFactors(n);
  
    // sorts the factors vector
    sort(factors.begin(), factors.end());
  
    // prints out the maximised product.
    cout << findProduct(n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of above approach 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
  
public class GFG {
  
// Declare the ArrayList of factors for storing the 
    static List< Integer> factors = new ArrayList<>();
  
// function to find out the factors of a number 
    static void findFactors(int n) {
        // we loop until the i reaches the sqrt(n) 
        for (int i = 1; i * i <= n; i++) {
  
            // we check if i is a factor of n 
            if (n % i == 0) {
  
                // if both the factors are same 
                // only push one factor 
                if ((n / i) == i) {
                    factors.add(factors.size(), i);
                } else {
  
                    // factor1 is pushed 
                    factors.add(factors.size(), n/i);
  
                    // factor2 is pushed 
                    factors.add(factors.size(), i);
                }
            }
        }
    }
  
// Function to find the maximum product 
    static int findProduct(int n) {
// initialise the product with -1 
        int product = -1;
        int si = factors.size();
  
        for (int i = 0; i < si; i++) {
            for (int j = 0; j < si; j++) {
                for (int k = 0; k < si; k++) {
  
                    // we find the sum of factors 
                    // and store it in s 
                    int s = factors.get(i) + factors.get(j) + factors.get(k);
  
                    // we check whether the fourth 
                    // factor exists or not 
                    if (Collections.binarySearch(factors, n - s) >= 0) {
                        // product of factors 
                        int p = factors.get(i) * factors.get(j) * factors.get(k) * (n - s);
  
                        // we check whether we have a better 
                        // p now if yes update 
                        if (p > product) {
                            product = p;
                        }
                    }
                }
            }
        }
  
        return product;
    }
  
    // Driver Code 
    public static void main(String[] args) {
        int n = 10;
  
        // intializes the vectors with the divisors of n 
        findFactors(n);
  
        // sorts the factors vector 
        Collections.sort(factors);
  
        // prints out the maximised product. 
        System.out.println(findProduct(n));
    }
}

chevron_right


Output:

20

Time Complexity: O((no.of divisors)^3 * log(no. of divisors))

Efficient Approach: This is the returned maximized product upto first 40 natural numbers.

1-> -1, 2-> -1, 3-> -1, 4-> 1 , 5-> -1 , 6-> 4, 7-> -1, 8-> 16, 9-> -1, 10-> 20, 11-> -1 12-> 81, 13-> -1, 14-> -1 , 15-> -1, 16-> 256, 17-> -1 18-> 324, 19-> -1, 20-> 625, 21-> -1, 22-> -1, 23-> -1, 24-> 1296, 25-> -1, 26-> -1 27-> -1, 28-> 2401, 29-> -1, 30-> 2500, 31-> -1, 32-> 4096, 33-> -1, 34-> -1 35-> -1, 36-> 6561, 37-> -1, 38-> -1, 39-> -1, 40-> 10000, 41-> -1, 42-> 9604

If we closely try to observe the pattern we can find out the pattern is somewhat common in some cases.
For example:

  1. For every odd number there is no solution, hence returns -1.
  2. There is no solution for numbers less than 4.
  3. For every number which is divisible by 4 the solution is always in the form of (n/4)^4.
    • the numbers like 4 which has factors {1, 2, 4} solution is 1 and (4/4)^4 = 1.
    • the numbers like 8 which has factors {1, 2, 4, 8} solution is 16 ans (8/4)^4 = 16.
  4. For every number which is divisible by 6 the solution is always in the form of (n/3)^2 * (n/6)^2
    • the numbers like 6 which has factors {1, 2, 3, 6} solution is 4 and (6/3)^2 * (6/6)^2 = 4.
    • the numbers like 18 which has factors {1, 2, 3, 6, 9, 18} solution is 324 and (18/3)^2 * (18/6)^2 = 324.
  5. For every number which is divisible by 10 the solution is always in the form of (n/10) * (n/5)^2 * (n/2)
    • the numbers like 10 which has factors {1, 2, 5, 10} solution is 20 and (10/10)*(10/5)^2 * (10/2) = 20.
    • the numbers like 20 which has factors {1, 2, 5, 10, 25, 50} solution is 12500 and (50/10)*(50/5)^2 *(50/2) = 12500.
  6. For every other even number there is no solution the numbers like 14 and 22.

Note: We consider the lowest factor which divides the number first and we ignore the next consecutive divisors in order to calculate the max product. For example, 12 is divisible by 4 and 6 both. But we consider the least factor to calculate so we consider 4 as its divisor for calculation of product.

Below is the implementation of above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
  
// For calculation of a^b
int modExp(int a, int b)
{
    int result = 1;
    while (b > 0) {
        if (b & 1)
            result = result * a;
        a = a * a;
        b /= 2;
    }
  
    return result;
}
  
// Function to check
int check(int num)
{
    // every odd and number less than 3.
    if (num & 1 || num < 3)
        return -1;
  
    // every number divisible by 4.
    else if (num % 4 == 0)
        return modExp(num / 4, 4);
  
    // every number divisble by 6.
    else if (num % 6 == 0)
        return modExp(num / 3, 2) * modExp(num / 6, 2);
  
    // every number divisible by 10.
    else if (num % 10 == 0)
        return modExp(num / 5, 2) * (num / 10) * (num / 2);
  
    // for every even number which is not
    // divisible by above values.
    else
        return -1;
}
  
// Driver code
int main()
{
    int num = 10;
    cout << check(num);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of above approach
import java.io.*;
import java.util.*;
import java.lang.*;
  
class GFG
{
// For calculation of a^b
static int modExp(int a, int b)
{
    int result = 1;
    while (b > 0
    {
        if (b == 1)
            result = result * a;
        a = a * a;
        b /= 2;
    }
  
    return result;
}
  
// Function to check
static int check(int num)
{
    // every odd and number less than 3.
    if (num == 1 || num < 3)
        return -1;
  
    // every number divisible by 4.
    else if (num % 4 == 0)
        return modExp(num / 4, 4);
  
    // every number divisble by 6.
    else if (num % 6 == 0)
        return modExp(num / 3, 2) * modExp(num / 6, 2);
  
    // every number divisible by 10.
    else if (num % 10 == 0)
        return modExp(num / 5, 2) * (num / 10) * (num / 2);
  
    // for every even number which is not
    // divisible by above values.
    else
        return -1;
}
  
// Driver code
public static void main(String[] args)
{
    int num = 10;
    System.out.print(check(num));
}
}
  
// This code is contributed 
// by Akanksha Rai(Abby_akku)

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of above approach
  
  
# For calculation of a^b
def modExp( a, b):
  
    result = 1
    while (b > 0): 
        if (int(b) & 1):
            result = result * a
        a = a * a
        b /= 2
      
  
    return result
  
  
# Function to check
def check( num):
  
    # every odd and number less than 3.
    if (num & 1 or num < 3):
        return -1
  
    # every number divisible by 4.
    elif (num % 4 == 0):
        return modExp(num / 4, 4)
  
    # every number divisble by 6.
    elif (num % 6 == 0):
        return modExp(num / 3, 2) * modExp(num / 6, 2)
  
    # every number divisible by 10.
    elif (num % 10 == 0):
        return modExp(num / 5, 2) * (num / 10) * (num / 2)
  
    # for every even number which is not
    # divisible by above values.
    else:
        return -1
  
  
# Driver code
if __name__=='__main__':
    num = 10
    print(int(check(num)))
  
# This code is contributed by ash264

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C#  implementation of above approach 
using System;
  
public class GFG{
    // For calculation of a^b 
static int modExp(int a, int b) 
    int result = 1; 
    while (b > 0) 
    
        if (b == 1) 
            result = result * a; 
        a = a * a; 
        b /= 2; 
    
  
    return result; 
  
// Function to check 
static int check(int num) 
    // every odd and number less than 3. 
    if (num == 1 || num < 3) 
        return -1; 
  
    // every number divisible by 4. 
    else if (num % 4 == 0) 
        return modExp(num / 4, 4); 
  
    // every number divisble by 6. 
    else if (num % 6 == 0) 
        return modExp(num / 3, 2) * modExp(num / 6, 2); 
  
    // every number divisible by 10. 
    else if (num % 10 == 0) 
        return modExp(num / 5, 2) * (num / 10) * (num / 2); 
  
    // for every even number which is not 
    // divisible by above values. 
    else
        return -1; 
  
// Driver code 
static public void Main (){
          
    int num = 10; 
    Console.WriteLine(check(num)); 
    

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// Php implementation of above approach 
  
// For calculation of a^b 
function modExp($a, $b
    $result = 1; 
    while ($b > 0) 
    
        if ($b & 1) 
            $result = $result * $a
        $a = $a * $a
        $b /= 2; 
    
  
    return $result
  
// Function to check 
function check($num
    // every odd and number less than 3. 
    if ($num & 1 || $num < 3) 
        return -1; 
  
    // every number divisible by 4. 
    else if ($num % 4 == 0) 
        return modExp($num / 4, 4); 
  
    // every number divisble by 6. 
    else if ($num % 6 == 0) 
        return modExp($num / 3, 2) * 
               modExp($num / 6, 2); 
  
    // every number divisible by 10. 
    else if ($num % 10 == 0) 
        return modExp($num / 5, 2) * 
                     ($num / 10) * ($num / 2); 
  
    // for every even number which is not 
    // divisible by above values. 
    else
        return -1; 
  
// Driver code 
  
$num = 10; 
echo check($num); 
      
// This code is contributed 
// by Shivi_Aggarwal
?>

chevron_right


Output:

20

Time Complexity: O(log N)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.