簊亍书丄旳峛孒,①個潲嶶攺進了①些旳冪運匴,加了一个简单的check,以及改成了位运算。
1: #include <stdio.h>
2: #include <stdlib.h>
3: #include <limits.h>
4:
5: unsigned long power(int base,int n)
6: {
7: //a simple check
8: if(base>=2 && n>=32)
9: {
10: printf("the result will exceed the limit of long:%u\n",ULONG_MAX);
11: exit(-1);
12: }
13:
14: if(n==0)
15: {
16: return 1;
17: }
18: else if(n==1)
19: {
20: return base;
21: }
22: else if((n & 1)==0)
23: {
24: return power(base*base,n>>1);
25: }
26: else if((n & 1)!=0)
27: {
28: return power(base*base,n>>1)*base;
29: }
30: else
31: {
32: //should not get here
33: return -1;
34: }
35: }