Find the maximum number of composite summands of a number in Python

PythonServer Side ProgrammingProgramming

Suppose we have a given number N that in range (1<=N<=10^9), we have to represent N as a sum of the largest possible number of composite summands and return this largest number, otherwise when we cannot find any split, then return -1.

So, if the input is like 16, then the output will be 4 as 16 can be written as 4 + 4 + 4 + 4 or 8 + 8, but (4 + 4 + 4 + 4) has maximum summands.

To solve this, we will follow these steps −

  • max_val := 16

  • Define a function pre_calc() . This will take

  • table := a list of size max_val, then store -1 at each position

  • table[0] := 0

  • v := [4, 6, 9]

  • for i in range 1 to max_val, increase by 1, do

    • for k in range 0 to 2, do

      • j := v[k]

      • if i >= j and table[i - j] is not -1, then

        • table[i] := maximum of table[i], table[i - j] + 1

  • return table

  • Define a function max_summ() . This will take table, n

  • if n < max_val, then

    • return table[n]

  • otherwise,

    • t := integer of ((n - max_val) / 4) + 1

    • return t + table[n - 4 * t]

  • From the main method, do the following −

  • table := pre_calc()

  • display max_summ(table, n)

Example 

Let us see the following implementation to get better understanding −

global max_val
max_val = 16
def pre_calc():
   table = [-1 for i in range(max_val)]
   table[0] = 0
   v = [4, 6, 9]
   for i in range(1, max_val, 1):
      for k in range(3):
         j = v[k]
         if (i >= j and table[i - j] != -1):
            table[i] = max(table[i], table[i - j] + 1)
   return table
def max_summ(table, n):
   if (n < max_val):
      return table[n]
   else:
      t = int((n - max_val) / 4)+ 1
      return t + table[n - 4 * t]
n = 16
table = pre_calc()
print(max_summ(table, n))

Input

16

Output

4
raja
Published on 20-Aug-2020 07:56:21
Advertisements