FACTORIAL(5) = 5 * FACTIORIAL(4) FACTORIAL(4) = 4 * FACTIORIAL(3)

19
Lecture 12 COP3502: Introduction to CIS I

Transcript of FACTORIAL(5) = 5 * FACTIORIAL(4) FACTORIAL(4) = 4 * FACTIORIAL(3)

Lecture 12COP3502: Introduction to CIS I

recursion

“defining a program in terms of itself”

“find your way home”

find your way home:if (you are at home) {

stop moving}else {

take one step towards home“find your way home”

}

“find your way home”

find your way home (stepsAway) :if (stepsAway == 0) {

stop moving}else {

take one step towards home“find your way home”(stepsAway – 1)

}

recursion requirements

base case – recursion ends

recursive call – function call on smaller problem

EVERY RECURSIVE CALL SHOULD BRING YOU CLOSER TO THE BASE CASE!

factorial

n! = n x (n-1) x (n-2) …. x 2 x 1

Ex. 5! = 5 x 4 x 3 x 2 x 1 = 120

factorial

n! = n x (n-1)!

5! = 5 x 4! = 5 x (4 x 3!)= 5 x (4 x (3 x 2!))

= 5 x (4 x (3 x (2 x 1!)))

FACTORIAL(5) = 5 * FACTIORIAL(4)

FACTORIAL(5) = 5 * FACTIORIAL(4)

FACTORIAL(4) = 4 * FACTIORIAL(3)

FACTORIAL(5) = 5 * FACTIORIAL(4)

FACTORIAL(4) = 4 * FACTIORIAL(3)

FACTORIAL(3) = 3 * FACTIORIAL(2)

FACTORIAL(5) = 5 * FACTIORIAL(4)

FACTORIAL(4) = 4 * FACTIORIAL(3)

FACTORIAL(3) = 3 * FACTIORIAL(2)

FACTORIAL(2) = 2 * FACTIORIAL(1)

FACTORIAL(5) = 5 * FACTIORIAL(4)

FACTORIAL(4) = 4 * FACTIORIAL(3)

FACTORIAL(3) = 3 * FACTIORIAL(2)

FACTORIAL(2) = 2 * FACTIORIAL(1)

FACTORIAL(1) = 1 * FACTIORIAL(0)

FACTORIAL(5) = 5 * FACTIORIAL(4)

FACTORIAL(4) = 4 * FACTIORIAL(3)

FACTORIAL(3) = 3 * FACTIORIAL(2)

FACTORIAL(2) = 2 * FACTIORIAL(1)

FACTORIAL(1) = 1 * FACTIORIAL(0)

FACTORIAL(0) = 1

BASE CASE!

Fibonacci

Fib(0) = 0Fib(1) = 1Fib(2) = 1Fib(3) = 2

…Fib(n) = Fib(n-1) + Fib(n-2)