Wednesday, February 21, 2024
HomeSoftware EngineeringHalving Sum in Python

Halving Sum in Python


The problem

Given a optimistic integer n, calculate the next sum:

n + n/2 + n/4 + n/8 + ...

All parts of the sum are the outcomes of integer division.

Instance

25  =>  25 + 12 + 6 + 3 + 1 = 47

The answer in Python code

Choice 1:

def halving_sum(n): 
    complete = [n]
    
    whereas n>=1:
        n = int(n/2)
        complete.append(n)
        
    return sum(complete)

Choice 2:

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

Choice 3:

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

Check circumstances to validate our resolution

@take a look at.describe('Instance Assessments')
def example_tests():
    take a look at.assert_equals(halving_sum(25),47)
    take a look at.assert_equals(halving_sum(127),247)
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments