Search⌘ K

Fibonacci and HCF (Recursion)

Explore how recursion works by implementing methods to find the nth Fibonacci number and the highest common factor using Ruby. Understand recursive parameters, base cases, and logic to solve problems efficiently.

Introduction to recursion

We want to explore the idea behind recursion by looking at a program that uses recursion for finding the nthn^{th} Fibonacci number. Before we explain what recursion is, let’s examine the formula for the nthn^{th} Fibonacci number:

fib(1) = 1
fib(2) = 1
fib(n) = fib(n-1) + fib(n-2)
Formula of N-th Fibonacci number

If we are asked the question: “what is the 6th6^{th} ...