Missing Number

Completed Code

var arr = [ 14, 5, 7, 4, 12, 1, 2, 10, 6, 8, 15, 3, 13, 9 ];
var upper = 15;
var lower = 1;

findMissingNumber(arr, upper, lower)

function findMissingNumber(arr, upper, lower) {
    var sumOfArray = 0;
    for (var i = 0; i < arr.length; i++) {
        sumOfArray += arr[i]
    }
    console.log(sumOfArray);

    upperSum = (upper * (upper + 1)) / 2;
    console.log(upperSum);

    lowerSum = (lower * (lower - 1)) / 2;
    console.log(lowerSum);

    theoreticalSum = upperSum - lowerSum;
    console.log(theoreticalSum);

    missingNumber = theoreticalSum - sumOfArray;
    console.log( missingNumber);
}

Variables

  • upper - the upper bound or largest value in our range.

  • lower - the lower bound or smallest value in our range.

  • sumOfArray - the sum of each of our array's elements.

  • upperSum - part of something called a Gauss Sum.

  • lowerSum - also part of the Gauss Sum.

  • theoreticalSum - what the sum of array would be if the missing number was one of the bounds.

  • missingNum - we get our missing number by subtracting the sum of the array without the missing number from our theoretical sum.

Gauss Sum

The Gauss Sum was originally developed by a famous mathematician to calculate the sum of the numbers from 1 to 100. The formula is written like this:

  • S - The total sum of the sequence

  • n - The number of terms in the series

    We use a variation of the Gauss Sum involving the lower bound and upper bound because there is a chance that the missing number could be the upper or lower bound.

Steps

  1. The application loops through the array, adding each element to the total sum. Our sumOfArray is 109.

  2. Using a variation of the Gauss Sum Formula we calculate the upper limit sum because there is a chance that the missing number could be our actual upper bound. Our upperSum is 120.

  3. Using a variation of the Gauss Sum Formula we calculate the lower limit sum because there is a chance that the missing number could be our actual lower bound. Our lowerSum is 0.

  4. We subtract the two to calculate the theoretical sum in case the missing number is the upper or lower bound.

  5. We subtract the sum of the array without the missing number from the theoretical sum to find our missing number.

Output

I logged each variable in the console so that if you don't get the same answer, you can more easily find where you messed up.

109
120
0
120
11

If you wanted to make the missing number one of the bounds, replace either the 1 or 15 with 11.

NOTE TO TESTER, DELETE WHEN FINISHED

Might need another look over on why we're actually using the variation of the Gauss Sum formula. I think I understand it, but I'm not 100%.

Last updated