【问题标题】:Exponents without using the pow() function不使用 pow() 函数的指数
【发布时间】:2013-11-16 04:15:33
【问题描述】:

例如pow(3,3) 返回 27

我尝试了while 并尝试了for 循环。我错过了一些明显的东西。只是不确定它是什么。有人能帮我看看吗?

$i = 1; 
while ($i <= $exponent) {
    $result = ($base * $base);
    $result = $result * $result;
    $i++;   
    echo $result;
}

【问题讨论】:

  • 您的实现只支持正整数指数。如果我想将2 提升到-1/2 怎么办?
  • 只需要支持正整数即可。
  • @minitech 我感觉想把电脑从厨房窗户“扔”出来,因为我很“累”。感谢您纠正这一点。我需要睡觉:/

标签: php algorithm math


【解决方案1】:

我真的不知道如何描述哪里出了问题,这里 - 你的代码对于计算指数没有意义。从 1 开始,乘以基数 $exponent 次。

$result = 1;

for ($i = 0; $i < $exponent; $i++) {
    $result *= $base;
}

echo $result;

【讨论】:

  • 虽然告诉初学者很好,但上面的实现效率很低,因为它需要 O(exponent)。
【解决方案2】:

这是非常有效的 pow 函数的递归伪代码:-

  pow(a,b) {

    if(b==0) return 1

    temp = pow(a,b/2)

    if(b%2==0)
      return(temp*temp)

    else return(a*temp*temp)

  }

上面的代码比for循环更直观,时间复杂度为O(logb)

我不熟悉php语法。

【讨论】:

    【解决方案3】:

    您想将一个数字乘以基数 exponent 次 - 所以是这样的:

    function myPow($base, $exponent) {
      $result = 1;
      for($ii = 0; $ii < $exponent; $ii++) {
        $result *= $base;
      }
      return $result;
    }
    

    已编辑 - 刚刚注意到 php 标签...

    【讨论】:

      【解决方案4】:

      有一个你可以使用的身份。

      xy=ey×ln(x)

      不知道怎么翻译成php。

      【讨论】:

        【解决方案5】:
        $x = 3; // 3*3*3*3*3  => 5 time 
        $n = 5;
        $res = 1;
        for ($i = 0; $i < $n; $i++)//i need 5time repeat
            {
            $res *= $x;
                //in here important
                // first time $res = 1 and $x = 3 ---> $res * $x --> 1*3 = 3
                //secend time $res = 3 and $x = 3 ---> $res * $x --> 3*3 = 9
                //next        $res = 9 and $x = 3 ---> $res * $x --> 9*3 = 27
                //next       $res = 27 and $x = 3 ---> $res * $x -> 27*3 = 81
                //final time $res = 81 and $x = 3 ---> $res * $x -> 81*3 = 243
            }
        echo $res;
        ///// Output : 243
        

        【讨论】:

          【解决方案6】:

          这个函数也应该知道可能的负指数

          function pow($num, $x)
          {
              if ($x == 0) return 1;
              else if ($x > 0) return $num * pow($num, --$x);
              else return 1 / $num * pow($num, ++$x);
          }
          

          pow(2, 3)8
          pow(2, -3)0.125 >

          【讨论】:

            【解决方案7】:
            function power($a,$b)
            {
                if ($b==0) return 1;
                if ($b==1) return $a;
                if ($b%2==0) return power ($a*$a,$b/2);
                return $a*power($a*$a,($b-1)/2);
            }
            
            $total= power(2,16);'
            

            可能上面的代码需要某人..

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2018-09-08
              • 2020-07-21
              • 1970-01-01
              • 2012-05-15
              • 2021-07-08
              • 2015-12-20
              • 2012-06-02
              相关资源
              最近更新 更多