在 JavaScript 中查詢陣列中的數字及其第 n 個倍數


我們需要編寫一個 JavaScript 函式,該函式將陣列中的整數作為第一個引數,將數字 n 作為第二個引數。

該函式應檢查陣列中是否存在兩個這樣的數字,其中一個是另一個數字的第 n 個倍數。

如果陣列中存在任何這樣的對,則該函式應返回 true,否則返回 false。

例如 −

如果陣列和數字為 −

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

則輸出應為 −

const output = true;

因為陣列和中存在數字 2 和 8 。

8 = 2 * 4

示例

下面是程式碼 −

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));

輸出

下面是控制檯輸出 −

true

更新於: 2021 年 1 月 22 日

143 次檢視

開啟你的 職業生涯

完成教程並獲得認證證書

開始
廣告
© . All rights reserved.