Finding a number and its nth multiple in an array in JavaScript


We are required to write a JavaScript function that takes in an array of integers as the first argument and a number, say n, as the second argument.

The function should check whether there exists two such numbers in the array that one is the nth multiple of the other.

If there exists any such pair in the array, the function should return true, false otherwise.

For example −

If the array and the number are −

const arr = [4, 2, 7, 8, 3, 9, 5];
const n = 4;

Then the output should be −

const output = true;

because there exist the numbers 2 and 8 in the array and.

8 = 2 * 4

Example

Following is the code −

const arr = [4, 2, 7, 8, 3, 9, 5];
const n = 4;
const containsNthMultiple = (arr = [], n = 1) => {
   const hash = new Set();
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      const [left, right] = [el / n, el * n];
      if(hash.has(left) || hash.has(right)){
         return true;
      };
   hash.add(el);
   };
   return false;
};
console.log(containsNthMultiple(arr, n));

Output

Following is the console output −

true

Updated on: 22-Jan-2021

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements