Search code examples
citerationpow

How do you calculate negative powers in C using iteration?


I'm writing a function in C that takes in a float base and int power, and calculates base^power

So far I have:

float powIteration(float base, int power){
    if (power == 0){
        return 1;
    }
    else if (power > 0){
         for (int i = 0; i <= power; i++){
            base *= base;
       }
        return base;
    }
    else if (power < 0){
        for (int i = 0; i <= power; i++){
            base *= base;
        }
        return 1/base;
    }
}

I've already solved this using recursion. But I also want to do it using iteration. But for some reason, this code results in stuff like 2^-2 = 0.5

Furthermore, would this method even fulfill what would be called an "iterative approach"?


Solution

  • Answered the last one instantly just by the first mistake I found, so I figured I'd go test and help you out with this.

    Firstly you are changing your base each iteration, and you don't want that, else you won't have a value to multiply every time, but one different every iteration. Just like pm100 said: you have to remember your original base. example: using base=2 and power=-3:

    i=0 -> base *= base; 2*2 = 4;
    i=1 -> now base is 4 so: 4*4 = 16;
    i=2 -> now base is 8 so: 8*8 = 64; and you want it to be 2*2*2
    

    and finally 1/value will give you the correct answer

    Also in your negative for loop: You are making your for loop start at 0, if your power is, let's say -2, then it doesn't meet your running condition i <= power because your i is always > power; should make it something like this:

    for (int i = power+1; i<0; i++)
    

    I did some changes for you:

    float powIteration(float base, int power){
        float num=base;
        if (power == 0){
            return 1;
        }else if (power > 0){
             for (int i = 1; i < power; i++){
                num=num*base;
           }
            return num;
        }else if (power < 0){
            for (int i = power+1; i<0; i++){
               num=num*base;
            }
            return 1/num;
        }
    }