Advertisement
makispaiktis

Maximize ab+bc+cd for standard sum of a,b,c,d

Oct 3rd, 2020 (edited)
1,418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. '''
  2. If a, b, c, d are positive integers with sum = 63 what is the maximum value
  3. of the expression ab + bc + cd
  4. '''
  5. from timeit import default_timer as timer
  6.  
  7. def maximize(sum):
  8.     maxExpression = 0
  9.     maxA = 0
  10.     maxB = 0
  11.     maxC = 0
  12.     maxD = 0
  13.     start = timer()
  14.     for a in range(1, sum):
  15.         for b in range(1, sum):
  16.             for c in range(1, sum):
  17.                 for d in range(1, sum):
  18.                     if a + b + c + d == sum:
  19.                         expression = a * b + b * c + c * d
  20.                         flag = True
  21.                         if expression > maxExpression:
  22.                             maxExpression = expression
  23.                             maxA = a
  24.                             maxB = b
  25.                             maxC = c
  26.                         maxD = d
  27.  
  28.     end = timer()
  29.     elapsed = end - start
  30.     print("We know that a,b,c,d > 0 and: a + b + c + d = " + str(sum))
  31.     print("The expression ab + bc + cd gets its maximum value for: ")
  32.     print("a = " + str(maxA) + ", b = " + str(maxB) + ", c = " + str(c) + ", d = " + str(d))
  33.     print("Max expression = " + str(maxExpression))
  34.     print("Execution time = " + str(round(elapsed, 2)) + " seconds.")
  35.     print()
  36.  
  37.  
  38. # MAIN FUNCTION
  39. SUM = list(range(5, 70, 5))
  40. for sum in SUM:
  41.     print("************************************************")
  42.     maximize(sum)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement