標籤:

數值的整數次方

數值的整數次方

數值是double類型,整數次方可能是負數0正數。

參考代碼:

root@gt:/home/git/Code# ./a.out base:2.000000 exponent:10 res:1024.000000 exponent:-10 res=0.000977root@gt:/home/git/Code# cat pow.c #include <stdio.h>int g_invalidInput = 0;int equal(double base,double n){ int res = base - n; if(res < 0) res = -res; if(res < 0.000001) return 1; else return 0;}double PowerUnsigned(double base,unsigned int absExponent){ double res = 1.0; while(absExponent) { res *= base; --absExponent; } return res;}double Power(double base,int exponent){ if(equal(base,0.0) && exponent < 0) { g_invalidInput = 1; printf("invalid input
"); return 0.0; } unsigned int absExponent = (unsigned int)exponent; if(exponent < 0) { absExponent = (unsigned int)(-exponent); } double res = PowerUnsigned(base,absExponent); if(exponent < 0) { res = 1.0/res; } return res;}int main(){ double base = 2.0; int exponent = 10; double res0 = Power(base,exponent); double res1 = Power(base,-exponent); printf("base:%lf exponent:%d res:%lf
exponent:%d res=%lf
",base,exponent,res0,-exponent,res1); return 0;}

擴展:

乘方演算法可以優化:

double PowerUnsigned(double base,unsigned int absExponent){ double res = 1.0; while(absExponent) { res *= base; --absExponent; } return res;}

可以使用一點技巧,更快的計算乘方:

double PowerUnsigned(double base,unsigned int absExponent){ if(absExponent == 0) return 1; if(absExponent == 1) retuen base; double res = PowerUnsigned(base,absExponent >> 1); res *= res; if(absExponent & 0x1 == 1) res *= base;//奇數 return res;}

推薦閱讀:

基數排序
6. ZigZag Conversion(medium) & 7.Reverse Integer(easy)
棧和隊列
期望為線性時間的選擇演算法
fibo數列第n項

TAG:演算法 | 筆試 |