Exponentiation algorithm

In programming there are not just 1 method to solve the problems for the exponential algorithm.What is exponential algorithm? Well is also can be mention as power. For example 2 to the power of 3 is 8 (2^3=8). Exponential algorithm is to find the value through computational way.

You can computed an exponential by iterative.
For example (in python):

def iterPower(base, exp):
    result=base
    if exp==0:
        return 1
    else:
        while exp>1:
            result*=base
            exp-=1
        return result

The code is like keep multiple the base number while minus the exponential value until the exp is 0.Is like 5^5=5*5*5*5*5

Above is an exponential by iteratively executing successive multiplications. Exponential can be computed in a recursive function.

def recurPower(base, exp):
    if exp==0:
        return 1
    else:
        return base*recurPower(base, exp-1)
The function is keep reuse , until the exp is equal to 0 and return 1.
For example 5^5:
It was something like
5(5^4)
5(5)(5^3)
5(5)(5)(5^2)
5(5)(5)(5)(5)(1)

The smallest value of exp is 0 in this case.

There are another method also could be use in recursive method but a different way

def recurPowerNew(base,exp):

    if (exp>0) and (exp%2==0):
        return recurPowerNew(base*base,(exp/2))

    elif exp>0 and exp%2!=0:
        return base*recurPowerNew(base,exp=exp-1)
    elif exp==0:
        return 1
        
From the code above, in the even part(Highlighter with grey), this method could help to reduce the recursive time thus increase the performance.

The concept is like 5^10 is equal to 25^5. if the using the first method it would like recursive 10 times will the second method only recursive for 5 times.



Comments

Popular posts from this blog

Reading and Writing Operation of SRAM

Transmission Control Protocol (TCP)

File transfer from android to linux