In this assignment, we'll practice the techniques learned in this lesson using the "Sum of Natural Numbers" problem. Try to solve the problem recursively on your own first. If it helps to start by writing an iterative solution, feel free to do so. Remember to write a complete 'Recursive Definition' before attempting a solution.
// Create a function that calculates the sum of the first `n`
// natural numbers. A natural number is a positive integer
// starting from 1. Therefore, the sum of the first `n` natural
// numbers is the sum of all integers from 1 to `n`.
// For example, if `n` is 5, the sum would be 1 + 2 + 3 + 4 + 5 == 15.
console.log(sumOfNaturalNumbers(1) === 1);
console.log(sumOfNaturalNumbers(5) === 15);
console.log(sumOfNaturalNumbers(10) === 55);
console.log(sumOfNaturalNumbers(20) === 210);
console.log(sumOfNaturalNumbers(0) === 0);
// All test cases should log true.
In recursive problem-solving, we typically define two key components: a recursive definition and a base case. The recursive definition breaks down the problem into smaller instances of the same problem, while the base case provides a simple, non-recursive termination condition.
The Base Case
The base case in this scenario occurs when the number n
is less than or equal to 1. In such cases, the sum of all natural numbers up to n
is n
itself. Although 0 is not traditionally a natural number, we include it here to handle edge cases effectively. This consideration is reflected in the last of our example test cases, where 0 is provided as input.
The Recursive Definition
In the case of summing the first n
natural numbers, our recursive definition is as follows: The sum of the first n natural numbers can be expressed as n plus the sum of the first n-1 natural numbers.
The solution becomes more attainable with a well-defined base case and a recursive definition.
function sumOfNaturalNumbers(n) {
if (n <= 1) {
return n;
}
return n + sumOfNaturalNumbers(n - 1);
}