Lesson 5
Simple Recursion in Practice
Lesson Overview

The topic of our lesson today is Simple Recursion in Practice. As you may already know, recursion is a fundamental concept in computer science and an essential skill to master for any serious programmer. Using recursion can simplify code and make it easier to understand, although it can sometimes be hard to grasp. Basically, it is a method where the solution to a problem is based on solving smaller instances of the same problem.

Quick Example

Let's quickly examine a factorial calculation, probably the most common and simple example of recursion. In math, the factorial of a number n is the product of all positive integers less than or equal to n. It sounds complicated, but if we think about it, the factorial of n can be calculated as the multiplication of the number n and the factorial of n - 1. So, in JavaScript, we can write a recursive function that calculates the factorial of a number. It will multiply the number by the factorial of number - 1 until it reaches 0. At this point, the function returns 1 (since the factorial of 0 is 1 by definition), which ends the recursion.

Here is how the solution will look:

JavaScript
1function factorial(n) { 2 // Base case: factorial of 0 is 1 3 if (n === 0) { 4 return 1; 5 } 6 // Recursive case: multiply n by factorial of n-1 7 else { 8 return n * factorial(n - 1); 9 } 10} 11 12// Example usage 13console.log(factorial(5)); // Outputs 120
Example with Memoization

To further illustrate the concept of recursion and introduce memoization, let's look at the Tribonacci sequence. The Tribonacci sequence is a generalization of the Fibonacci sequence where each term is the sum of the three preceding terms. The sequence starts with 0, 1, and 1, and proceeds as follows: 0, 1, 1, 2, 4, 7, 13, ...

To find the nth number in the Tribonacci sequence, we can use recursion with memoization to optimize our solution.

Here is how the solution will look:

JavaScript
1function tribonacci(n, memo = {}) { 2 // Check if the result is already in the memo 3 if (n in memo) { 4 return memo[n]; 5 } 6 // Base cases 7 if (n === 0) { 8 return 0; 9 } else if (n === 1 || n === 2) { 10 return 1; 11 } 12 // Recursive case with memoization 13 memo[n] = tribonacci(n - 1, memo) + tribonacci(n - 2, memo) + tribonacci(n - 3, memo); 14 return memo[n]; 15} 16 17// Example usage 18console.log(tribonacci(5)); // Outputs 7
Next: Practice!

Understanding recursion is crucial, as it's applied in many areas of computer science, like algorithms, data structures, etc. This lesson was just a warm-up. Now, it's time to practice to solidify your understanding and further build upon this knowledge. Remember, practice is the key!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.