How to usethe Mathematical Formulae in Javascript
Expected Sum = (n * (n + 1)) / 2
- n is the highest number in the range.
- Add 1 to n to include it in the summation.
- Multiply n by (n + 1).
- Divide the result by 2 to get the expected sum.
In this approach, we find the Sum of the Natural number of 1 to 100 using the sum of natural number formulae n(n+1)/2.After the sum of the natural number. Then calculate the sum of the given elements of the array. Now Subtract the sum of natural numbers – the sum of the given elements of the array. Then It will give the missing number.
Syntax:
const sumOfFirstN = (n * (n + 1)) / 2;
Example: In this example, we are using the above-explained approach.
function findMissingNumber(arr) {
const n = 100;
const sumOfFirstN = (n * (n + 1)) / 2;
const sumOfArray =
arr.reduce((acc, num) => acc + num, 0);
const missingNumber =
sumOfFirstN - sumOfArray;
return missingNumber;
}
const array =
Array.from({ length: 99 }, (_, index) => index + 1);
const missingNumber = findMissingNumber(array);
console.log("Missing number is:", missingNumber);
Output
Missing number is: 100
JavaScript Program to Find the Missing Number in a Given Integer Array of 1 to 100
In this article, we are going to find the missing number in a given integer array of 1 to 100 in JavaScript, Given an array [] of size 100 with integers in the range of [1, 100], There are no duplicate values in the array and no larger value than the size of the array. The task is to print that which is missing value in the array.
Let’s take an example:
Input: arr[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, /* Missing number */,12, /* ... */, 100]; Size of an array is 100
Output: 11
Explanation: The missing number between 1 to 100 is 11
There are several methods that can be used to find the missing number in a given integer array of 1 to 100 in JavaScript, which are listed below:
Table of Content
- Approach 1: Using the Mathematical Formulae
- Approach 2: Using the array iteration
- Approach 3: Using Object
- Approach 4: Using Bit Manipulation (XOR)
We will explore all the above methods along with their basic implementation with the help of examples.
Contact Us