Write a function to return the base to the power of its exponent?

First write the function and then suggest the PHP buit-in method for this.

Train Asked on October 31, 2015 in PHP.
Add Comment
  • 1 Answer(s)
    Best answer

    You must write it as a recursive function in order to get the base multiplied by the exponent recursively.

    
    function power($num, $pow) {
    
    if ($pow < 1)
    
    return 1;
    
    else
    
    return $num * power($num, $pow-1);
    
    }
    //echo power(2, 3);
    //echo pow(2, 3); // This is the php built-in method
    //echo 2 ** 3; //This is beyond php 5.6
    

     

    Train Answered on October 31, 2015.
    Add Comment

    Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.