日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > php >内容正文

php

php实现数值的整数次方

發布時間:2025/3/17 php 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 php实现数值的整数次方 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

php實現數值的整數次方

一、總結

沒有考慮到指數為負數的情況

?

二、php實現數值的整數次方

題目描述:

給定一個double類型的浮點數base和int類型的整數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.全面考察指數的正負、底數是否為零等情況。 3 * 2.寫出指數的二進制表達,例如13表達為二進制1101。 4 * 3.舉例:10^1101 = 10^0001*10^0100*10^1000。 5 * 4.通過&1和>>1來逐位讀取1101,為1時將該位代表的乘數累乘到最終結果。 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]; //這樣就不用寫那個賦初值記憶化數組為-1的循環了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

這是因為數組沒定義這個數組的偏移量,也就是

?

轉載于:https://www.cnblogs.com/Renyi-Fan/p/9054798.html

總結

以上是生活随笔為你收集整理的php实现数值的整数次方的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。