Last active
April 5, 2021 14:42
-
-
Save FelixLuciano/c538b7e80f753ee2557a379f7f5a18a9 to your computer and use it in GitHub Desktop.
rendezvous with cassidoo #190 - Interview question of the week
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* From: https://buttondown.email/cassidoo/archive/to-understand-is-to-invent-jean-piaget/ | |
* @param {number} n Integer | |
* @param {number[]} primes Sorted array of prime integers | |
* @returns {number} Return the nth positive number whose all prime factors are in the array primes. | |
* @example | |
* $ superUgly(1, [2, 3, 5]) | |
* -> 1 | |
* | |
* $ superUgly(11, [2, 7, 13, 19]) | |
* -> 49 | |
*/ | |
function superUgly (n, primes) { | |
const base = primes.length | |
let quocient = n - 1 | |
let ugly = 1 | |
while (quocient > 0) { | |
const remaining = (quocient - 1) % base | |
const index = remaining | |
const number = primes[index] | |
quocient = Math.floor((quocient - 1) / base) | |
ugly = ugly * number | |
} | |
return ugly | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment