w3resource

JavaScript: Check sum of consecutive positive integers

JavaScript Math: Exercise-73 with Solution

Express as Sum of Consecutive Integers

Write a JavaScript program to check if a given positive integer can be expressed as the sum of two or more consecutive positive integers.

Sample Data:
33 can be represented as 11 + 22
10 = 1+2+3+4
but 8 cannot be represented in this way.

Sample Solution-1:

JavaScript Code:

/**
 * Checks if a given number is not a power of two.
 * @param {number} n - The number to check.
 * @returns {boolean} - True if the number is not a power of two, false otherwise.
 */
function test(n)
{
  // Perform bitwise AND operation between n and n - 1, and check if the result is not zero
  return (n & (n - 1)) != 0;
}

// Test the function with different numbers
console.log(test(33)); // Output: true
console.log(test(10)); // Output: true
console.log(test(8));  // Output: false

Output:

true
true
false

Flowchart:

JavaScript Math flowchart of all prime factors of a given number

Live Demo:

See the Pen javascript-math-exercise-73-1 by w3resource (@w3resource) on CodePen.


Sample Solution-2:

JavaScript Code:

/**
 * Checks if a given number is not a power of two.
 * @param {number} n - The number to check.
 * @returns {boolean} - True if the number is not a power of two, false otherwise.
 */
function test(n){
  // Calculate the base-2 logarithm of n and check if it's not an integer
  return !Number.isInteger(Math.log2(n));
}

// Test the function with different numbers
console.log(test(33)); // Output: true
console.log(test(10)); // Output: true
console.log(test(8));  // Output: false

Output:

true
true
false

Flowchart:

JavaScript Math flowchart of all prime factors of a given number

Live Demo:

See the Pen javascript-math-exercise-73-2 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that checks if a positive integer can be expressed as the sum of two or more consecutive positive integers.
  • Write a JavaScript function that finds one possible sequence of consecutive integers whose sum equals a given number.
  • Write a JavaScript function that returns all possible sequences of consecutive numbers that sum to the given integer.
  • Write a JavaScript function that validates input and handles cases where no consecutive sequence exists for the given number.

Go to:


PREV : Check Pronic Number.
NEXT : Hexadecimal to Binary Conversion.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.