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

PythonServer Side ProgrammingProgramming

Suppose we have a number N; we have to find factors of N and return only 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 50625 as all the factors are → 1 2 3 4 5 6 10 12 15 20 30 60 and their product is 50625, as we 15 has been selected four times to make product largest.

To solve this, we will follow these steps −

  • my_map := a new map

  • v := a new list, v1 := a new list

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

    • if n mod i is same as 0, then

      • insert i at the end of v

      • if i is not same as integer part of (n / i) and i is not same as 1, then

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

  • s := size of v

  • maximum := -1

  • map1 := an array of size (n + 5) fill this with 0

  • for i in range 0 to s, do

    • for j in range i to s, do

      • if v[i] + v[j] < n , then

        • insert v[i] + v[j] at the end of v1

        • map1[v[i] + v[j]] := [v[i], v[j]]

        • my_map[v[i] + v[j]] := 1

  • s := size of v1

  • for i in range 0 to s, do

    • element := n - (v1[i])

    • if element in my_map, then

      • a := map1[v1[i], 0]

      • b := map1[v1[i], 1]

      • c := map1[n - v1[i], 0]

      • d := map1[n - v1[i], 1]

      • maximum := maximum of a * b * c * d, maximum

  • if maximum is same as -1, then

    • display "Not Possible"

  • otherwise,

    • display maximum

Example

Let us see the following implementation to get better understanding −

 Live Demo

from math import sqrt, ceil, floor
def get_product(n):
   my_map = dict()
   v = []
   v1 = []
   for i in range(1,ceil(sqrt(n)) + 1):
   if (n % i == 0):
      v.append(i)
      if (i != (n // i) and i != 1):
         v.append(n // i)
   s = len(v)
   maximum = -1
   map1 = [0]*(n + 5)
   for i in range(s):
      for j in range(i, s):
         if (v[i] + v[j] < n):
            v1.append(v[i] + v[j])
            map1[v[i] + v[j]] =[v[i], v[j]]
            my_map[v[i] + v[j]] = 1
   s = len(v1)
   for i in range(s):
      element = n - (v1[i])
      if (element in my_map):
         a = map1[v1[i]][0]
         b = map1[v1[i]][1]
         c = map1[n - v1[i]][0]
         d = map1[n - v1[i]][1]
         maximum = max(a * b * c * d, maximum)
   if (maximum == -1):
      print("Not Possible")
   else :
      print("Maximum product", maximum)
n = 60
get_product(n)

Input

60

Output

Maximum product 50625
raja
Published on 25-Aug-2020 09:15:48
Advertisements