丑陋超级数 - 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.