Skip to content

Instantly share code, notes, and snippets.

@FermiDirak
Created September 22, 2019 04:00
Show Gist options
  • Save FermiDirak/8d605615be7cb8c356613e4f43763b9e to your computer and use it in GitHub Desktop.
Save FermiDirak/8d605615be7cb8c356613e4f43763b9e to your computer and use it in GitHub Desktop.
var nthUglyNumber = function(n, a, b, c) {
const inputs = [a, b, c];
const curr = [a, b, c];
let counter = n;
while (counter !== 1) {
const sorted = curr.slice().sort((a, b) => a > b ? 1 : -1);
let min = sorted[0];
let minIndex = curr.findIndex((a) => a === min);
let mid = sorted[1];
let step = Math.floor((mid - min) / inputs[minIndex]) - 1;
step = Math.min(step, counter - 1);
step = Math.max(step, 1);
curr[minIndex] += inputs[minIndex] * step;
counter -= step;
for (let i = 0; i < curr.length; ++i) {
if (curr[i] === min) {
curr[i] += inputs[i];
}
}
}
return Math.min(...curr);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment