// // main.m // c++test // // Created by andyyang on 6/3/13. // Copyright (c) 2013 andyyang. All rights reserved. // //#import <Foundation/Foundation.h> #include "stdio.h" #include "string.h" int power(double base,int exponent) { if(exponent==0) { return 1; } if(exponent==1) { return base; } if(exponent &0x01) { return power(base,exponent>>1)*power(base,exponent>>1)*base; }else { return power(base,exponent>>1)*power(base,exponent>>1); } } int main(int argc, const char * argv[]) { double ret=power(12, 2); printf("%f",ret); getchar(); return 0; } // // main.m // c++test // // Created by andyyang on 6/3/13. // Copyright (c) 2013 andyyang. All rights reserved. // //#import <Foundation/Foundation.h> #include "stdio.h" #include "string.h" int power(double base,int exponent) { if(exponent==0) { return 1; } if(exponent==1) { return base; } if(exponent &0x01) { return power(base,exponent>>1)*power(base,exponent>>1)*base; }else { return power(base,exponent>>1)*power(base,exponent>>1); } } int main(int argc, const char * argv[]) { double ret=power(12, 2); printf("%f",ret); getchar(); return 0; }
充分利用位運算,高效低實現數值的整數次方