Skip to content

Instantly share code, notes, and snippets.

@ooade
Last active October 20, 2020 17:44
Show Gist options
  • Save ooade/a6f5a78e3edd355cbcaeaa366962bff2 to your computer and use it in GitHub Desktop.
Save ooade/a6f5a78e3edd355cbcaeaa366962bff2 to your computer and use it in GitHub Desktop.
Project Euler 12 JavaScript Solution
var x = 0, y = 1;
while (factors(x).length <= 500) {
x += y;
y++;
}
console.log(x);
function factors(n) {
let arr = [], i = 1, max = n;
while (i < max) {
if (n % i === 0) {
arr.push(i); // i is a factor, pass it the array;
let k = n / i; // k is also a factor
if (i !== k) {
arr.push(k); // only push k if it's not the current i
}
max = k;
}
i++;
}
return arr.sort((a, b) => a - b);
}
@zachlearnscode
Copy link

Great solution to cut max down each time through the loop. I had a solution that worked with smaller numbers, but couldn't produce the answer to the PE question. I let the code run for two hours. I plugged your factors function in, and it found the answer instantly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment