Member-only story
Basic of Recursion (Before start on Dynamic Programing)
2 min readNov 21, 2024
Write a recursive function sumOfDigits
that takes a positive integer n
and returns the sum of its digits.
sumOfDigits(123); // Output: 6 (1 + 2 + 3)
sumOfDigits(456); // Output: 15 (4 + 5 + 6)
sumOfDigits(9); // Output: 9
function sumOfDigits(n) {
// Base case: If n is a single digit
if (n < 10) {
return n;
}
// Recursive case: Sum the last digit and recurse on the rest
return (n % 10) + sumOfDigits(Math.floor(n / 10));
}
// Test cases
console.log(sumOfDigits(123)); // 6
console.log(sumOfDigits(456)); // 15
console.log(sumOfDigits(9)); // 9
Write a recursive function factorial
to calculate the factorial of a number n
.
factorial(5); // Output: 120 (5 * 4 * 3 * 2 * 1)
factorial(0); // Output: 1
function factorial(n) {
if (n === 0) return 1; // Base case
return n * factorial(n - 1); // Recursive case
}
console.log(factorial(5)); // 120
console.log(factorial(0)); // 1
Write a recursive function fibonacci
to return the nth Fibonacci number.
fibonacci(5); // Output: 5 (0, 1, 1, 2, 3, 5)
fibonacci(7); // Output: 13
function fibonacci(n) {
if (n === 0) return 0; // Base case 1
if (n === 1) return 1; //…