Halving Sum in Python

The challenge

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
Code language: PHP (php)

The solution in Python code

Option 1:

def halving_sum(n): total = [n] while n>=1: n = int(n/2) total.append(n) return sum(total)
Code language: Python (python)

Option 2:

def halving_sum(n): s=0 while n: s+=n ; n>>=1 return s
Code language: Python (python)

Option 3:

def halving_sum(n): if n == 1: return 1 else: return n + halving_sum(n//2)
Code language: Python (python)

Test cases to validate our solution

@test.describe('Example Tests') def example_tests(): test.assert_equals(halving_sum(25),47) test.assert_equals(halving_sum(127),247)
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments