Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 245
  • Last Modified:

python recursion, example in php

I am having trouble understanding recursion in python because I can not relate to php (a language I am more familiar)

http://www.experts-exchange.com/Programming/Languages/Scripting/Python/Q_28489785.html
0
rgb192
Asked:
rgb192
  • 2
  • 2
1 Solution
 
aikimarkCommented:
how would you generate an Nth Fibonacci number in PHP (with or without recursion)?
0
 
rgb192Author Commented:
how would you generate an Nth Fibonacci number in PHP (with or without recursion)?

I do not know.
0
 
aikimarkCommented:
How about calculating the factorial of a number?  This is the product of all the integers between that number and 1.
Example:
5! = 5*4*3*2*1 = 120
A PHP example of a recursive function that calculates the factorial of the number passed to it:
function fact($number) { 
    if ($number === 0) { 
        return 1; 
    } 
    else { 
        return ($number * fact($number-1)); 
    } 
}

Open in new window

Once we get down to 1 we will always be multiplying by 1, so we might be a bit more efficient if we write it as
function fact($number) { 
    if ($number < 2) { 
        return 1; 
    } 
    else { 
        return ($number * fact($number-1)); 
    } 
}

Open in new window

In both cases, we have some conditional test that stops the recursion.
0
 
rgb192Author Commented:
thanks.

recursion example works
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now