How to implement an integer based power function pow(int, int) in C

1 Answer

0 votes
#include <stdio.h>
 
int intpow(int base, int exp) {
    int power = 1;
    
    while (1) {
        if (exp & 1)
            power *= base;
        exp >>= 1;
        if (!exp)
            break;
        base *= base;
    }
 
    return power;
}
 
int main()
{
    printf("%d\n", intpow(2, 3));  // 8
    printf("%d\n", intpow(3, 3));  // 27
    printf("%d\n", intpow(3, 2));  // 9
    printf("%d\n", intpow(2, 2));  // 4
    printf("%d\n", intpow(5, 2));  // 25
    printf("%d\n", intpow(-2, 4)); // 16
     
    return 0;
}

 
 
/*
run:
  
8
27
9
4
25
16
 
*/

 



answered May 31, 2018 by avibootz
edited Jun 10 by avibootz
...