Super Ugly Numbers JavaScript

JavascriptWeb DevelopmentFront End Technology

<h2>Super Ugly Number</h2><p>Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly numbers given primes = [2, 7, 13, 19] of size 4.</p><h2>Problem</h2><p>We are required to write a JavaScript function that takes in number, num, as the first argument and an array, arr, of prime numbers as the second argument. The function should find and return the (num)th super ugly number.</p><h2>Example</h2><p>The code for this will be &minus;</p><pre class="prettyprint notranslate">const num = 7; const arr = [2, 7, 14, 19]; const superUgly = (num = 1, arr = []) =&gt; { &nbsp; &nbsp;arr.sort((a, b)=&gt; a - b); &nbsp; &nbsp;const ptr = []; &nbsp; &nbsp;const res = []; &nbsp; &nbsp;for(let i=0;i&lt;arr.length;i++){ &nbsp; &nbsp; &nbsp; ptr[i] = 0; &nbsp; &nbsp;}; &nbsp; &nbsp;res.push(1); &nbsp; &nbsp;for(let i = 1; i &lt; num; i++){ &nbsp; &nbsp; &nbsp; let mn=Math.pow(2, 32) - 1; &nbsp; &nbsp; &nbsp; for(let j = 0; j &lt; arr.length; j++){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;mn=Math.min(mn,arr[j]*res[ptr[j]]) &nbsp; &nbsp; &nbsp; }; &nbsp; &nbsp; &nbsp; res[i]=mn &nbsp; &nbsp; &nbsp; for(let j=0; j &lt; arr.length; j++){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(mn % arr[j] === 0){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ptr[j]++; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}; &nbsp; &nbsp; &nbsp; }; &nbsp; &nbsp;}; &nbsp; &nbsp;return res[num-1] }; console.log(superUgly(num, arr));</pre><h2>Output</h2><p>And the output in the console will be &minus;</p><pre class="result notranslate">16</pre>
raja
Updated on 20-Mar-2021 05:46:18

Advertisements