How to Calculate A to the power B without use of multiplication and divsion operator?

Viewed 169

I need to find A raise to the power b, simply power ( a, b ) without the use of multiplication and division operator

Ex: pow ( 2, 3 ) = 8

I am unable to understand the intuition behind this code.

int pow(int a, int b)  
{  
    if (b == 0)  
        return 1;  
    int answer = a;  
    int increment = a;  
    int i, j;  
    for(i = 1; i < b; i++)  
    {  
        for(j = 1; j < a; j++)  
        {  
            answer += increment;  
        }  
        increment = answer;  
    }  
    return answer;  
}
3 Answers

well the inner loop multiplies a by itself by adding it to itself a times.

the outer loop does this b times

It works like this:

If the exponent is zero you just return 1. Otherwise you need to do a calculation.

The inner loop, i.e.

for(j = 1; j < a; j++)  
{  
    answer += increment;  
}  

performs a multiplication. The result of executing that code is equivalent to

answer += increment * a;

And the outer loop is repeating that multiplication b - 1 times (because answer starts as a, so you need one less multiplication as if you were starting with answer = 1), I.e. in total you get

answer += ((a * a) * a ) ... *a

for b-1 times in total, which is equivalent to a^b.

...power ( a, b ) without the use of multiplication and division operator

To avoid multiplication, note that 3 x 5 means either 3+3+3+3+3 or 5+5+5.

For power, note that 3 ^ 3 (i.e. 3 cubed) means 3 x 3 x 3. The multiplications in this product can be replaced with additions (i.e. 3 x 3 => 3+3+3, and then 9 x 3 = 9+9+9 = 27).

Related