[Solved] Javascript – loops [closed]


Suppose there are n people attending this quiz, the # of the winner is x.

So the sum of people entering before the winner is the sum of 1+...+(x-1),
the sum of people entering after the winner is the sum of (x+1)+...+n.

Here we have 1+...+(x-1) = (x+1)+...+n, which derives to (x*(x-1))/2 = ((x+n+1)*(n-x))/2. Simplifying this, we have 2*x^2-n^2-n = 0.

So in javascript, we write as:

for (var n=67; n<=670; n++) {
    for (var x=1; x<=n; x++){
        if (2*x*x-n*n-n == 0)
            console.log(n,x);
    }
}

The answer is simple: there are 288 people for the quiz, and the winner is #204.

Type the code in any modern browser should be fine.

1

solved Javascript – loops [closed]