Find four factors of N with maximum product and sum equal to N - Set-2 in Python Program


Suppose we have a number N, we have to find all factors of N and return the product of four factors of N such that: The sum of the four factors is same as N. The product of the four factors is maximum. All four factors can be equal to each other to maximize the product.

So, if the input is like N = 60, then the output will be All the factors are -> 1 2 3 4 5 6 10 12 15 20 30 60 and product is 50625, as we 15 has been selected four times to make product largest.

To solve this, we will follow these steps −

  • factors := a new list

  • for i in range 1 to integer of (square root of n) + 1, do

    • if n mod i is same as 0, then

      • insert i at the end of factors

      • insert integer of (n / i) at the end of factors

  • sort the list factors

  • display factors

  • final_prod := 1, flag := 1

  • for i in range 0 to size of factors, do

    • for j in range i to size of factors, do

      • for k in range j to size of factors, do

        • y := n - factors[i] - factors[j] - factors[k]

        • if y <= 0, then

          • come out from the loop

        • if n mod y is same as 0, then

          • flag := 0

  • final_prod := maximum of factors[i] * factors[j] * factors[k] * y, final_prod

  • if flag is same as 0, then

    • display final_prod

  • otherwise,

    • display "Not possible"

Example

Let us see the following implementation to get better understanding −

 Live Demo

from math import *
def get_factors(n) :
   factors = []
   for i in range(1, int(sqrt(n)) + 1) :
      if n % i == 0 :
         factors.append(i)
         factors.append(n // i)
   factors.sort()
   print("Factors are ", factors)
   final_prod = 1
   flag = 1
   for i in range(0, len(factors)) :
      for j in range(i, len(factors)) :
         for k in range(j, len(factors)) :
            y = n - factors[i] - factors[j] - factors[k]
            if y <= 0 :
               break
            if n % y == 0 :
               flag = 0
               final_prod = max(factors[i] * factors[j] * factors[k] * y , final_prod)
   if flag == 0 :
      print("Product is", final_prod)
   else :
      print("Not possible")

n = 60
get_factors(n)

Input

60

Output

Factors are [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60] Product is 50625

Updated on: 25-Aug-2020

61 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements