Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Given a positive integer n, calculate the following sum:
- n + n/2 + n/4 + n/8 + ...
- All elements of the sum are the results of integer division.
- Example
- 25 => 25 + 12 + 6 + 3 + 1 = 47
- '''
- def halving_sum(n):
- maxPower = 0
- while int(n / 2**maxPower) != 0:
- maxPower += 1
- sum = 0
- for i in range(0, maxPower+1):
- sum += int(n / 2**i)
- return sum
- # MAIN FUNCTION
- print(halving_sum(9))
- print(halving_sum(25))
- print(halving_sum(127))
- print(halving_sum(1))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement