w3resource

JavaScript: Find the maximum integer n

JavaScript Basic: Exercise-145 with Solution

Max n for 1+2+...+n ≤ Value

Write a JavaScript program to find the maximum integer n such that 1 + 2 + ... + n <= a given integer.

Sample Solution:

JavaScript Code:

/**
 * Function to find the sum of natural numbers up to a given value
 * @param {number} val - The value up to which the sum of natural numbers needs to be calculated
 * @returns {number} - The number of terms in the sum sequence
 */
function sumn(val) {
  var sn = 0; // Initialize the sum of natural numbers
  var i = 0; // Initialize the index to 0
  
  // Loop to calculate the sum of natural numbers up to a certain limit
  while (sn <= val) {
    sn += i++; // Incrementally add the value of 'i' to the sum and increment 'i'
  }
  
  return i - 2; // Return the number of terms in the sum sequence (subtracting 2 to account for the extra iteration)
}

// Display the number of terms for different values
console.log(sumn(11)); // Output: 4
console.log(sumn(15)); // Output: 5 

Output:

4
5

Live Demo:

See the Pen javascript-basic-exercise-145 by w3resource (@w3resource) on CodePen.

Flowchart:

Flowchart: JavaScript - Find the maximum integer n

ES6 Version:

/**
 * Function to find the sum of natural numbers up to a given value
 * @param {number} val - The value up to which the sum of natural numbers needs to be calculated
 * @returns {number} - The number of terms in the sum sequence
 */
const sumn = (val) => {
  let sn = 0; // Initialize the sum of natural numbers
  let i = 0; // Initialize the index to 0
  
  // Loop to calculate the sum of natural numbers up to a certain limit
  while (sn <= val) {
    sn += i++; // Incrementally add the value of 'i' to the sum and increment 'i'
  }
  
  return i - 2; // Return the number of terms in the sum sequence (subtracting 2 to account for the extra iteration)
};

// Display the number of terms for different values
console.log(sumn(11)); // Output: 4
console.log(sumn(15)); // Output: 5

For more Practice: Solve these Related Problems:

  • Write a JavaScript program that finds the maximum integer n such that the sum 1 + 2 + ... + n does not exceed a given value.
  • Write a JavaScript function that iteratively sums consecutive integers until the total exceeds a target, then returns the last valid n.
  • Write a JavaScript program that uses a loop to determine the largest n for which the cumulative sum is within a specified limit.

Go to:


PREV : Break URL into Parts.
NEXT : Sum of Cubes from 1 to n.

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.