The content this article brings to you is about how PHP realizes the integer power of numerical values (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be useful to you. Helps.
Given a floating-point number base of type double and an integer exponent of type int. Find the exponent power of base.
Idea:
1. The binary expression of the exponent to the power of 10^6 can represent 10^110 (binary) 10^100 * 10^10 * 10^000=>10^4 * 10^2
2. Shift operation
while(n!=0){ if((n&1)==1) res*=curr; curr*=curr;// 翻倍 n>>=1;// 右移一位 }
<?php function Power($base, $n){ $res = 1; $curr = $base; $exponent; if($n>0){ $exponent = $n; }else if($n<0){ if($base==0) return 0; $exponent = -$n; }else{// n==0 return 1;// 0的0次方 } //$exponent转成二进制,有多少位就循环多少次,curr就执行n+1次方,如果当前位是1的就结果相乘 while($exponent!=0){ if(($exponent&1)==1) $res*=$curr; $curr*=$curr;// 翻倍 //var_dump($curr); $exponent>>=1;// 右移一位 } return $n>=0?$res:(1/$res);//指数是负数的情况 } $a=Power(10,6); var_dump($a); ~
The above is the detailed content of How to implement integer power of numerical value in php (code example). For more information, please follow other related articles on the PHP Chinese website!