Halving Sum in Python

0 min read 104 words

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

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)

Option 2:

def halving_sum(n): 
    s=0
    while n: 
        s+=n ; n>>=1
    return s

Option 3:

def halving_sum(n): 
    if n == 1:
        return 1
    else:
        return n + halving_sum(n//2)

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)
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts