php实现数值的整数次方
生活随笔
收集整理的這篇文章主要介紹了
php实现数值的整数次方
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
php實現(xiàn)數(shù)值的整數(shù)次方
一、總結(jié)
沒有考慮到指數(shù)為負數(shù)的情況
?
二、php實現(xiàn)數(shù)值的整數(shù)次方
題目描述:
給定一個double類型的浮點數(shù)base和int類型的整數(shù)exponent。求base的exponent次方。代碼一(phpAC):
1 <?php 2 3 function Power($base, $exponent) 4 { 5 6 if($exponent >= 0){ 7 $res = 1; 8 while($exponent >= 1){ 9 $res = $res * $base; 10 $exponent--; 11 } 12 return $res; 13 } 14 if($exponent < 0){ 15 $exponent2 = abs($exponent); 16 $res = 1; 17 while($exponent2 >=1){ 18 $res = $res *$base; 19 $exponent2--; 20 } 21 return 1/$res; 22 23 } 24 25 }?
代碼二(javaAC):
1 /** 2 * 1.全面考察指數(shù)的正負、底數(shù)是否為零等情況。 3 * 2.寫出指數(shù)的二進制表達,例如13表達為二進制1101。 4 * 3.舉例:10^1101 = 10^0001*10^0100*10^1000。 5 * 4.通過&1和>>1來逐位讀取1101,為1時將該位代表的乘數(shù)累乘到最終結(jié)果。 6 */ 7 public double Power(double base, int n) { 8 double res = 1,curr = base; 9 int exponent; 10 if(n>0){ 11 exponent = n; 12 }else if(n<0){ 13 if(base==0) 14 throw new RuntimeException("分母不能為0"); 15 exponent = -n; 16 }else{// n==0 17 return 1;// 0的0次方 18 } 19 while(exponent!=0){ 20 if((exponent&1)==1) 21 res*=curr; 22 curr*=curr;// 翻倍 23 exponent>>=1;// 右移一位 24 } 25 return n>=0?res:(1/res); 26 }?
代碼三(php快速冪):
<?php//算法:肯定用快速冪啊 $arr = array(1);//還是寫記憶化遞歸 function Power($base, $exponent) {global $arr;$arr[1]=$base;if($arr[$exponent]) return $arr[$exponent]; //這樣就不用寫那個賦初值記憶化數(shù)組為-1的循環(huán)了else{if($exponent%2==1) return $arr[$exponent]=Power($base, intval($exponent/2))*Power($base, intval($exponent/2))*$base;else return $arr[$exponent]=Power($base, intval($exponent/2))*Power($base, intval($exponent/2));} }這個代碼-2,3都沒過
2,-3也過不了
?
四、其它
Notice: Undefined offset: 14 in D:\software\code\phpStudy2018\PHPTutorial\WWW\index.php on line 8Notice: Undefined offset: 7 in D:\software\code\phpStudy2018\PHPTutorial\WWW\index.php on line 8Notice: Undefined offset: 3 in D:\software\code\phpStudy2018\PHPTutorial\WWW\index.php on line 8 16384Array ( [0] => 1 [1] => -2 [3] => -8 [7] => -128 [14] => 16384 ) Hello World這是因為數(shù)組沒定義這個數(shù)組的偏移量,也就是
?
轉(zhuǎn)載于:https://www.cnblogs.com/Renyi-Fan/p/9054798.html
總結(jié)
以上是生活随笔為你收集整理的php实现数值的整数次方的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 企业服务器备份
- 下一篇: recyclerview 设置分割线的高