Home > Backend Development > PHP Tutorial > How to implement integer power of numerical value in php (code example)

How to implement integer power of numerical value in php (code example)

不言
Release: 2023-04-04 12:42:02
forward
2937 people have browsed it

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;// 右移一位
}
Copy after login

<?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);
~
Copy after login

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!

Related labels:
php
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template