How do you do exponentiation in C?

前端 未结 7 1504
执笔经年
执笔经年 2020-12-05 06:31

I tried \"x = y ** e\", but that didn\'t work.

7条回答
  •  感动是毒
    2020-12-05 07:00

    pow only works on floating-point numbers (doubles, actually). If you want to take powers of integers, and the base isn't known to be an exponent of 2, you'll have to roll your own.

    Usually the dumb way is good enough.

    int power(int base, unsigned int exp) {
        int i, result = 1;
        for (i = 0; i < exp; i++)
            result *= base;
        return result;
     }
    

    Here's a recursive solution which takes O(log n) space and time instead of the easy O(1) space O(n) time:

    int power(int base, int exp) {
        if (exp == 0)
            return 1;
        else if (exp % 2)
            return base * power(base, exp - 1);
        else {
            int temp = power(base, exp / 2);
            return temp * temp;
        }
    }
    

提交回复
热议问题