Advertisement
makispaiktis

Codewars: Halving Sum

Jun 17th, 2020 (edited)
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.50 KB | None | 0 0
  1. '''
  2. Given a positive integer n, calculate the following sum:
  3. n + n/2 + n/4 + n/8 + ...
  4. All elements of the sum are the results of integer division.
  5. Example
  6. 25  =>  25 + 12 + 6 + 3 + 1 = 47
  7. '''
  8.  
  9. def halving_sum(n):
  10.     maxPower = 0
  11.     while int(n / 2**maxPower) != 0:
  12.         maxPower += 1
  13.     sum = 0
  14.     for i in range(0, maxPower+1):
  15.         sum += int(n / 2**i)
  16.     return sum
  17.  
  18. # MAIN FUNCTION
  19. print(halving_sum(9))
  20. print(halving_sum(25))
  21. print(halving_sum(127))
  22. print(halving_sum(1))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement