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
Check three consecutive numbers - JavaScript
We are required to write a JavaScript function that takes in a Number, say n, and we are required to check whether there exist such three consecutive natural numbers (not decimal/floating point) whose sum equals to n.
If there exist such numbers, our function should return them, otherwise it should return false. Following is the code ?
How It Works
For three consecutive numbers to sum to n, we need: x + (x+1) + (x+2) = n, which simplifies to 3x + 3 = n. Therefore, n must be divisible by 3 and greater than 5 (since the smallest three consecutive natural numbers are 1, 2, 3).
Example
const sum = 54;
const threeConsecutiveSum = sum => {
if(sum < 6 || sum % 3 !== 0){
return false;
}
// three numbers will be of the form:
// x + x + 1 + x + 2 = 3 * x + 3
const residue = sum - 3;
const num = residue / 3;
return [num, num+1, num+2];
};
console.log(threeConsecutiveSum(sum));
Output
Following is the output in the console ?
[ 17, 18, 19 ]
Testing Different Cases
console.log(threeConsecutiveSum(6)); // [1, 2, 3] console.log(threeConsecutiveSum(15)); // [4, 5, 6] console.log(threeConsecutiveSum(30)); // [9, 10, 11] console.log(threeConsecutiveSum(5)); // false (too small) console.log(threeConsecutiveSum(7)); // false (not divisible by 3)
[ 1, 2, 3 ] [ 4, 5, 6 ] [ 9, 10, 11 ] false false
Key Points
- The sum must be at least 6 (minimum consecutive numbers: 1, 2, 3)
- The sum must be divisible by 3
- The first number is calculated as (sum - 3) / 3
Conclusion
This function efficiently determines if a number can be expressed as the sum of three consecutive natural numbers by checking divisibility and calculating the starting number mathematically.
