在 JavaScript 中找到滿足特定條件的最小數字


我們需要編寫一個 JavaScript 函式,它將一個數字作為第一個引數(例如 n),並將一個數字陣列作為第二個引數。該函式應該返回最小的 n 位數字,它應該等於陣列中指定的所有元素的倍數。

如果不存在這樣的 n 位元素,那麼我們應該返回最小的此類元素。

例如:如果陣列為 -

const arr = [12, 4, 5, 10, 9]

對於 n = 2 和 n = 3,

輸出

輸出應該為 -

180

因此,讓我們為此函式編寫程式碼 -

示例

程式碼如下 -

const arr = [12, 4, 5, 10, 9]
const num1 = 2;
const num2 = 3;
const allDivides = (arr, num) => arr.every(el => num % el === 0);
const smallestMultiple = (arr, num) => {
   let smallestN = Math.pow(10, (num - 1));
   while(!allDivides(arr, smallestN)){
      smallestN++;
   };
   return smallestN;
};
console.log(smallestMultiple(arr, num1));
console.log(smallestMultiple(arr, num2));

輸出

控制檯中的輸出為 -

180
180

更新於: 17-Oct-2020

186 人次瀏覽

開啟你的事業

完成課程獲得認證

開始
廣告
© . All rights reserved.