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
Returning the nth even number using JavaScript
We are required to write a JavaScript function that takes in a number n and returns the nth even number in the sequence of natural numbers.
Problem
Given a positive integer n, find the nth even number. For example, the 1st even number is 2, the 2nd even number is 4, the 3rd even number is 6, and so on.
Understanding the Pattern
Even numbers follow a simple pattern: 2, 4, 6, 8, 10, 12... The nth even number can be calculated using the formula: n × 2.
Example Implementation
Here's how to implement this solution:
const num = 67765;
const nthEven = (n = 1) => {
return n * 2;
};
console.log(`The ${num}th even number is: ${nthEven(num)}`);
The 67765th even number is: 135530
Step-by-Step Examples
Let's verify with smaller numbers to understand the pattern:
const nthEven = (n) => n * 2;
// Test with first few even numbers
console.log("1st even number:", nthEven(1)); // 2
console.log("2nd even number:", nthEven(2)); // 4
console.log("3rd even number:", nthEven(3)); // 6
console.log("5th even number:", nthEven(5)); // 10
console.log("10th even number:", nthEven(10)); // 20
1st even number: 2 2nd even number: 4 3rd even number: 6 5th even number: 10 10th even number: 20
Alternative Approach with Validation
Here's a more robust version with input validation:
const findNthEven = (n) => {
if (n <= 0 || !Number.isInteger(n)) {
return "Please provide a positive integer";
}
return n * 2;
};
console.log(findNthEven(100)); // 200
console.log(findNthEven(-5)); // Please provide a positive integer
console.log(findNthEven(0)); // Please provide a positive integer
console.log(findNthEven(1.5)); // Please provide a positive integer
200 Please provide a positive integer Please provide a positive integer Please provide a positive integer
Conclusion
Finding the nth even number is straightforward using the formula n × 2. This mathematical approach is more efficient than iterating through numbers to count even ones.
