Jump to content

Recursion


web4

Recommended Posts

<?php

 

function getGCF($a,$b) {

echo "$b<br />";

if($b==0)

  return $a;

else

  return getGCF($b,$a % $b);

}

 

echo getGCF(6,10)."answer<br />";

 

?>

 

10

6

4

2

0

2answer

10

6

4

2

0

 

My problem is why did 10,6,4,2,0 appear?? i thought the output would be 0,2,4,6,10 cause that's the way recursion works....like in this example..

 

function nfact($n)

{

  if ($n == 0)

  {

    return 1;

  }

  else

  {

    return $n * nfact($n - 1);

  }

}

 

the way the recursion works in that program is they return the previous value of the function and that was my expectation in the first script...how did that happen? thanks

 

Link to comment
https://forums.phpfreaks.com/topic/197613-recursion/
Share on other sites

When debugging cases like this, it's useful to keep track of what your function does step bt step

getGCF(6,10)        $a = 6;  $b = 10; -> echo $b prints '10'; getGCF(10, 6%10) is called

getGCF(10, 6%10)    $a = 10; $b = 6;  -> echo $b prints '6'; getGCF(6,10%6) is called

getGCF(6,10%6)      $a = 6;  $b = 4;  -> echo $b prints '4'; getGCF(4,6%4) is called

getGCF(4,6%4)        $a = 4;  $b = 2;  -> echo $b prints '2'; getGCF(2,4%2) is called

getGCF(2,4%2)        $a = 2;  $b = 0;  -> echo $b prints '0'; 2 is returned

Link to comment
https://forums.phpfreaks.com/topic/197613-recursion/#findComment-1037198
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.