Optimized python program to find power of a number

def power(a,b):
        if a==0: return 0
        elif b==0: return 1
        elif b==1: return a
        elif b%2 == 0:
                res_even = power(a,b/2)
                return res_even*res_even
        else :
                b=(b-1)/2
                res_odd= power(a,b)
                return a*res_odd*res_odd

pow = power(2,10)
print pow
             #pow = 1024

The best way to find power of a number is to use recursion ( other than using library function). If we use normal recursion as
def power(a,b):
    if b==0: return 1
    else : return a*power(a,b-1)
,the calculation requires as many function call as ‘b’,and this will worsen the condition when we have to find the power of larger numbers.We can simplify this problem by considering the clue : 2^8 = (2^ 4)^2.

Advertisements

2 thoughts on “Optimized python program to find power of a number

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s