Power Using Recursion

1
2
3
4
5
6
7
8
9
10
11
12
int power(int m, int n){
if(n==0)
return 1;
else
return power(m, n-1)*m;
}

int main(int argc, const char * argv[]) {
printf("%d\n", power(2, 5));
return 0;
}

Faster solution

1
2
3
4
5
6
7
8
9
10
11
12
13
int power(int m, int n){
if(n==0)
return 1;
if(n%2==0)
return power(m*m, n/2);
else
return m*power(m*m, (n-1)/2);
}

int main(int argc, const char * argv[]) {
printf("%d\n", power(2, 5));
return 0;
}