Docsity

Understanding Recursive Functions: Factorial and Fibonacci Examples, Slides of Computer Fundamentals

Partial preview of the text

Download Understanding Recursive Functions: Factorial and Fibonacci Examples and more Slides Computer Fundamentals in PDF only on Docsity!

Recursion

• Recursive functions

  • Functions that call themselves
  • Can only solve a base case
  • The function launches a new copy of itself (recursion step)

to solve what it cannot do

  • Eventually base case gets solved
    • Gets plugged in, works its way up and solves whole problem

Example Using Recursion:

Factorial

• Example: factorials

  • 5! = 5 * 4 * 3 * 2 * 1

– Notice that

– Can compute factorials recursively

– Solve base case (1! = 0! = 1) then plug in

Call Sequence

Factorial ( 5 ) if 5 = 1 return 1 else return 5 * Factorial (4) Factorial ( 4 ) if 4 = 1 return 1 else return 4 * Factorial (3) Factorial ( 3 ) if 3 = 1 return 1 else return 3 * Factorial (2) Factorial ( 2 ) if 2 = 1 return 1 else return 2 * Factorial (1) Factorial ( 1 ) if 1 = 1 return 1 else return 5 * Factorial (4) 1 24 6 2

Example Using Recursion: The Fibonacci Series

  • Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
    • Each number is the sum of the previous two
    • Can be solved recursively:
      • Fib( n ) = Fib( n - 1 ) + Fib( n – 2 )
    • Code for the Fibonacci function Fibonnaci (n) 1. if n ≤ 2
      1. return n- 3. else 4. return Fibonnaci (n-1) + Fibonacci (n-2)

Fib ( 5 ) if 5 = 1 or 5 = 2 return 5- else return Fib (4) + Fib (3) Fib ( 4 ) if 4 = 1 or 4 = 2 return 4- else return Fib (3) + Fib (2) Fib ( 3 ) if 3 = 1 or 3 = 2 return 3- else return Fib (2) + Fib (1) Fib ( 2 ) if 2 = 1 or 2 = 2 return 2- else return Fib (1) + Fib (0) Fib ( 3 ) if 3 = 1 or 3 = 2 return 3- else return Fib (2) + Fib (1) Fib ( 2 ) if 2 = 1 or 2 = 2 return 2- else return Fib (1) + Fib (0) Fib ( 1 ) if 1 = 1 or 1 = 2 return 1- else return Fib (0) + Fib (-1) Fib ( 1 ) if 1 = 1 or 1 = 2 return 1- else return Fib (0) + Fib (-1) Fib ( 2 ) if 2 = 1 or 2 = 2 return 2- else return Fib (1) + Fib (0) 1 0 1 1 1 0 2 1 3