如何使用PHP创建自己的pow功能?

aya*_*ane 2 php algorithm math logic function

我想创建一个函数,其中我放了两个值(值及其功率 - 示例函数:multiply(3, 3)结果27).到目前为止我已经尝试但失败了,我使用谷歌进行了搜索,但我找不到任何结果,因为我不知道这个函数的名称.

我想要的完全是:

3,3 => 3×3×3 = 27
4,4 => 4×4×4×4 = 256

我尝试了什么:

function multiply($value,$power){
    for($x = 1; $x <= $value; $x++ ){
        return $c = $value * $power;
    }   
}
echo multiply(3,3);
Run Code Online (Sandbox Code Playgroud)

Jua*_*pes 9

答案已被接受,但我不得不来这里说这里的所有答案都使用了一个糟糕的算法.有更好的.包括非常简单的那些,例如通过平方取幂,将复杂度从O(功率)降低到O(log(功率)).

这个想法是在将指数除以2的同时对基数进行平方.例如

3^8 = 9^4 = 81^2 = 6561
Run Code Online (Sandbox Code Playgroud)

指数为奇数时有一种特殊情况.在这种情况下,您必须存储一个单独的变量来表示此因子:

2^10 = 4^5 = 16^2 * 4 = 256 * 4 = 1024
Run Code Online (Sandbox Code Playgroud)

PHP不是我强大的技能之一,但最终的算法很简单:

function multiply($value, $power){
    $free = 1;
    while ($power > 1) {
        if ($power % 2 == 1)
            $free *= $value;
        $value *= $value;
        $power >>= 1; //integer divison by 2
    }
    return $value*$free;
}
echo multiply(3, 3) . "\n";
echo multiply(2, 10) . "\n";
echo multiply(3, 8) . "\n";
Run Code Online (Sandbox Code Playgroud)


Han*_*nky 5

Oopsika,再清楚不过的问题了。使用名为pow的内置函数(在很多语言中)

echo pow(3, 3);
Run Code Online (Sandbox Code Playgroud)

编辑

让我们创建自己的函数。

function raiseToPower($base,$exponent)
{
    // multiply the base to itself exponent number of times
    $result=1;
    for($i=1;$i<=$exponent;$i++)
    {
      $result = $result * $base;  
    }
    return $result;
}
Run Code Online (Sandbox Code Playgroud)