Advertisement
makispaiktis

Codewars - Sum(1 to n) - a - b = a * b

Jan 7th, 2021 (edited)
861
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1. '''
  2. A friend of mine takes a sequence of numbers from 1 to n (where n > 0).
  3. Within that sequence, he chooses two numbers, a and b.
  4. He says that the product of a and b should be equal to the sum of all numbers in the sequence, excluding a and b.
  5. Given a number n, could you tell me the numbers he excluded from the sequence?
  6. '''
  7.  
  8. # Function 1
  9. def removeABfromSum(n):
  10.     if n <= 1 or n != int(n):
  11.         print("Error while using the function '" + removeABfromSum.__name__ + "'")
  12.         return -1000000
  13.     SUM = n * (n + 1) / 2
  14.     solA = -1000
  15.     solB = -1000
  16.     for a in range(1, n+1):
  17.         b = (SUM - a) / (a + 1)
  18.         if b == int(b) and b > a and b <= n:
  19.             # That means that the pair (a,b) is a solution of this problem
  20.             # The value of a and b remain! So, I will break the loop in order to gain time
  21.             solA = int(a)
  22.             solB = int(b)
  23.             break
  24.     return int(SUM), solA, solB
  25.  
  26.  
  27. # Function 2
  28. def prettyPrint(n):
  29.     SUM, solA, solB = removeABfromSum(n)
  30.     if solA == -1000 and solB == -1000:
  31.         print("n = " + str(n) + " ----> sum = " + str(SUM) + " ----> No solutions a,b")
  32.     else:
  33.         print("n = " + str(n) + " ----> sum = " + str(SUM) + " ----> a = " + str(solA) + ", b = " + str(solB))
  34.  
  35.  
  36. # MAIN FUNCTION
  37. nList = list(range(2, 101))
  38. for n in nList:
  39.     prettyPrint(n)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement