醜陋超級數 - JavaScript


醜陋超級數

醜陋超級數是指一個正數,其全部質因數都包含在大小的質數列表 primes 中。例如,[1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] 是一個包含 12 個醜陋超級數的序列,且 primes = [2, 7, 13, 19],大小為 4。

問題

我們要求寫一個 JavaScript 函式,其第一個引數為 num,第二個引數為一個包含質數的陣列,arr。此函式應該找到並返回第 (num) 個醜陋超級數。

示例

對應的程式碼如下 −

const num = 7;
const arr = [2, 7, 14, 19];
const superUgly = (num = 1, arr = []) => {
   arr.sort((a, b)=> a - b);
   const ptr = [];
   const res = [];
   for(let i=0;i<arr.length;i++){
      ptr[i] = 0;
   };
   res.push(1);
   for(let i = 1; i < num; i++){
      let mn=Math.pow(2, 32) - 1;
      for(let j = 0; j < arr.length; j++){
         mn=Math.min(mn,arr[j]*res[ptr[j]])
      };
      res[i]=mn
      for(let j=0; j < arr.length; j++){
         if(mn % arr[j] === 0){
            ptr[j]++;
         };
      };
   };
   return res[num-1]
};
console.log(superUgly(num, arr));

輸出

控制檯中的輸出將是 −

16

更新於: 2021 年 3 月 20 日

139 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.