0

The question as per the practice course is :

Write a JavaScript program to find the maximum integer n such that (1 + 2 + ... + n <= given integer ) is true. For eg. If a given integer is 10, value of maximum integer n is 4 so that 1+2+3+4 <= 10 is true. Your output code should be in the format console.log("Value of n is ", variableName)

My code is :

var num = prompt("Enter a number");

function test(x) {
  var sum = 1,
    n = 1,
    a = 0;
  while (sum <= x) {
    sum += n;
    n = n + 1;
    a += 1;

  }
  return a;
}
var output = test(num);
console.log("Result is :", output);

I'm getting the correct outputs as per the test cases I've entered(10-4,15-5,16-6,17-6) but the website says there is something wrong with the program.

What am i doing wrong?

3
  • which website ? Not getting your point completely Commented Feb 20, 2019 at 5:27
  • 1
    Your code doesn't fully work though - enter 4 and you get 3, but 1+2+3 = 6. Commented Feb 20, 2019 at 5:28
  • Also for 16 result should be 5 and not 6! Commented Feb 20, 2019 at 5:40

8 Answers 8

2

Better answer than looping: exploit maths. Starting with Triangular number formula:

1 + 2 + ... + n = n * (n + 1) / 2

Thus, for input x, you need to find n such that

n * (n + 1) / 2 <= x

To solve this, we need to clean up the inequality, then use the quadratic equation formula:

n^2 + n <= 2x
n^2 + n - 2x <= 0

n <= (-1 + sqrt(1 + 8x)) / 2

as the final solution. e.g. for

x = 10: n <= (-1 + sqrt(81)) / 2; n <= 4
x = 16: n <= (-1 + sqrt(128)) / 2; n <= 5.156854249492381

Round the upper limit down, and you have the largest allowed integer. Translated into JavaScript:

function test(x) {
  return Math.floor((Math.sqrt(8 * x + 1) - 1) / 2);
}

var num = prompt("Enter a number");
console.log("Result is :", test(num));

Sign up to request clarification or add additional context in comments.

5 Comments

It's a practice course where he's learning this skill. I don't think he's just trying to get this done, but instead trying to learn looping (at least that was the intended purpose). This is just purely getting this done
@AniketG: I partially disagree. First of all, there are other answers showing how to make looping code work. Second, if he's using one of the automated test platforms, many of them (like Project Euler) require you to not do the brute force approach because for some problems time limit is set low enough that time runs out before brute force search can complete, and coders are encouraged to think about algorithms and mathematical structure of the problem to qualify for the completion, not just code up the first (and least efficient) thing that pops into their mind.
tl;dr: Teaching JavaScript = teaching syntax. Teaching coding = teaching thinking.
I never thought about it that way. Good thinking
I didn't read the question properly as I focused on while in the question title. Using the mathematical approach almost always yields a quicker and more efficient result. I agree that applying it where possible will lead to a much more fruitful programming experience that is able to quickly tackle technical and theoretical problems
1

Consider if the passed value is 11. Then, the maximum integer n should be 4, because 1+2+3+4 < 11 is true, while 1+2+3+4+5 < 11 is false. Your current code outputs 5 for an input of 11, though, which is incorrect; your while loop is sometimes overshooting sum.

You also need to initialize sum to start at 0, not at 1.

Subtract one from a before returning it:

function test(x) {
  var sum = 0,
    n = 1,
    a = 0;
  while (sum <= x) {
    sum += n;
    n = n + 1;
    a += 1;
    console.log(a, sum);
  }
  return a - 1;
}
console.log(test(10));
console.log(test(11));

var num = prompt("Enter a number");
var output = test(num);
console.log("Result is :", output);

1 Comment

@JoachimIsaksson please reconsider your comment given the edit
0

The code below should work for you. Basically, what I did was that if the input is 10, and your sum is 9, it will still go into the while loop. Then it will add n again and now your number is greater than your input (which is 10), but you still return it. Here what I did is that at the end of the while loop, if your sum is greater than your input, subtract one from a. That way it will still execute, but it will fix the problem.

Also another error I noticed was that sum started at 1, and n started at 1. You wanted 1+2+3+...+n, however using your previous method, you got 1+1+2+3+...+n.

var num = prompt("Enter a number");

function test(x) {
  var sum = 0,
    n = 1,
    tempSum = 1,
    a = 0;
  while (sum <= x) {
    sum += n;
    n++;
    a++;
    if (sum > x) {
      a--;
    }
  }
  return a;
}
var output = test(num);
console.log("Result is :", output);

4 Comments

Good answer, this can be improved by reducing the number of variables used
@vol7ron I tried to keep this as similar to the original question.
Good point, sometimes the most concise answer is not the best for the question being asked, nice job
@vol7ron Thanks. In many cases, I use var instead of let and don't use some shorthand techniques. I try to keep my code as similar and using the same terms as the question so they understand it.
0

Your order of operation is a little funky; all you have to do is add the incrementor. The while false case will make sure the sum only passes over the number once. So when you return, reduce the number by one:

var num = prompt("Enter a number");
var output = test(num);
console.log("Result is :", output);


function test(num){
  let sum = 0
  let inc = 0
  while(sum<=num)
    sum+=++inc

  return --inc;
}

Comments

0

This is a reduced version of your code, basically we increment first the number to add (n) in each iteration, and then we add it to the variable holding the sum. When the loop conditions evaluates to false you need to decrement one to n to get your value:

var num = prompt("Enter a number");

function test(x)
{
    var sum = 0, n = 0;

    while (sum <= x)
    {
        sum += (++n);
    }

    return --n;
}

var output = test(num);
console.log("Result is :", output);

Comments

0

I think this will work for you:

var num = prompt("Enter a number");

function test(x) {
  var sum = 1,
    n = 0;
    
  while ((sum+n) <= x) {
    n = n + 1;
    sum += n;
  }
  return n;
}
var output = test(num);
console.log("Result is :", output);

Comments

0

Try below function to find max Number

function maxNumber(a){
 var i=1,sum=0,maxNumber=0;
 while(sum<=a) { 
     sum=sum+i; 
     if(sum<=a) 
      { 
        maxNumber=i;
      }
      i+=1;
   } 
   return maxNumber;
} 

doubled checked condition sum<=a to preserve the previous loop value and if condition not satisfied that means current loop value is not useful so returned preserved value of previous loop

Output tested :

enter image description here

Comments

0

Below will help you get the job done.

var num = prompt("Enter a number");

function findMaxNumber(num){
	var sum = 0;
	var counter = 0;
	while(sum < num){
        if(sum + counter > num){
            break; // Exit loop
        }
        sum = sum + counter;
        counter++;
	}
	return --counter; // Loop will cause this to be 1 higher than the max int.
}
console.log('Result is: ' + findMaxNumber(num));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.