Search code examples
javascriptnested-loops

Javascript - loops


I wonder if someone would be kind enough to demonstrate the use of loop and other functions in "javascript" by answering this question:

there is a nationwide math quiz; minimum 67, maximum 670 people have earned the right to attend. Each contestant is given an entry number to the hall where the quiz takes place (first to enter the hall gets 1, second 2 and so on). the winner was asked his entry # to the hall after the announcements. his response: the sum of the people before me and the sum of the people after me are equal; that's how you can find my entry #.

I hope I was able to word it properly.

I remember having tackled this question around early 1970's without success on my part but then asked my brothers engineering student friends; they all attacked it with enthusiasm only to give up in disgust after a couple of hours (with one Texas Instruments red light calculator with buttons that used to stick!). I have found the answer in later years but without the help of programming. The formula (n*(n+1))/2 obviously helps quite a bit when summing.

Thank you for your time.

Andrew


Solution

  • 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.