Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Sum of even numbers up to using recursive function in JavaScript
We have to write a recursive function that takes in a number n and returns the sum of all even numbers up to n.
A recursive function calls itself with modified parameters until it reaches a base case. For summing even numbers, we'll start from the largest even number ? n and work our way down.
How It Works
The algorithm follows these steps:
- If the input number is odd, we adjust it to the nearest even number below it
- Add the current even number to the sum and recursively call with the next smaller even number
- Continue until we reach 0 (base case)
Example
const recursiveEvenSum = (num, sum = 0) => {
num = num % 2 === 0 ? num : num - 1;
if(num){
return recursiveEvenSum(num - 2, sum + num);
}
return sum;
};
console.log(recursiveEvenSum(12));
console.log(recursiveEvenSum(122));
console.log(recursiveEvenSum(23));
console.log(recursiveEvenSum(10));
console.log(recursiveEvenSum(19));
42 3782 132 30 90
Step-by-Step Breakdown
Let's trace through recursiveEvenSum(10):
// Call 1: recursiveEvenSum(10, 0)
// num = 10 (even), sum = 0
// Return recursiveEvenSum(8, 10)
// Call 2: recursiveEvenSum(8, 10)
// num = 8, sum = 10
// Return recursiveEvenSum(6, 18)
// Call 3: recursiveEvenSum(6, 18)
// num = 6, sum = 18
// Return recursiveEvenSum(4, 24)
// Call 4: recursiveEvenSum(4, 24)
// num = 4, sum = 24
// Return recursiveEvenSum(2, 28)
// Call 5: recursiveEvenSum(2, 28)
// num = 2, sum = 28
// Return recursiveEvenSum(0, 30)
// Call 6: recursiveEvenSum(0, 30)
// num = 0 (falsy), return sum = 30
console.log("Sum of even numbers up to 10:", recursiveEvenSum(10));
Sum of even numbers up to 10: 30
Alternative Approach
Here's a cleaner version without the second parameter:
const simpleEvenSum = (num) => {
// Base case
if (num <= 0) return 0;
// If odd, make it even
if (num % 2 !== 0) num--;
// Add current even number + sum of remaining even numbers
return num + simpleEvenSum(num - 2);
};
console.log("Using simpler approach:");
console.log(simpleEvenSum(12)); // 2+4+6+8+10+12
console.log(simpleEvenSum(23)); // 2+4+6+...+22
console.log(simpleEvenSum(10)); // 2+4+6+8+10
Using simpler approach: 42 132 30
Conclusion
Recursive functions for summing even numbers work by breaking the problem into smaller subproblems. The key is identifying the base case (when to stop) and how to reduce the problem size in each recursive call.
Advertisements
