
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements