A
A
Adil16032020-05-09 19:54:41
PHP
Adil1603, 2020-05-09 19:54:41

How is this function performed?

Can you please tell me how this recursive function is performed, raising a number to a power?

<?php
function myRecursion($x, $n) {
  if ($n == 0) {
    return 1;
  }
  if ($n < 0) {
    return myRecursion(1/$x, -$n);
  }
  return $x * myRecursion($x, $n-1);
}

var_dump(myRecursion(5, 3));
?>


After bringing $n to zero and the function returns 1, what happens? in this code why write myRecursion($x, $n-1) and not myRecursion($n-1)
return $x * myRecursion($x, $n-1);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Boris Korobkov, 2020-05-09
@BorisKorobkov

how is this recursive function performed, raising a number to a power?

First you need to remember the math:
x^n = x * x^(n-1)
x^0 = 1
After adjusting $n to zero and the function returns 1, what happens?

myRecursion($x, 0) returns 1
turns out to be x*1, this is returned in response to the call to myRecursion($x, 1)
turns out to be x*x, this is returned in response to the call to myRecursion($x, 2)
and so on.
why write myRecursion($x, $n-1) and not myRecursion($n-1)

because this function should have two parameters, not one

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question