Skip to content

Instantly share code, notes, and snippets.

@evanlouie
Last active May 8, 2018 02:51
Show Gist options
  • Save evanlouie/676b811162993ead6b54f46ea21ba769 to your computer and use it in GitHub Desktop.
Save evanlouie/676b811162993ead6b54f46ea21ba769 to your computer and use it in GitHub Desktop.
Project Euler solutions in JS
// Some of these answers will only run in Firefox (browsers which support TCO)
/**
* Problem 1
* If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
* Find the sum of all the multiples of 3 or 5 below 1000.
*/
const problem1 = () => {
return Array(1000)
.fill(null)
.map((_, index) => index + 1)
.filter(num => num % 3 === 0 || num % 5 === 0)
.reduce((sum = 0, num) => sum + num);
};
/**
* Problem 2
* Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
* 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
* By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
*/
const problem2 = () => {
const fibs = function*() {
const fib = (n, a = 1, b = 2) => {
if (n === 1) {
return a;
} else if (n === 2) {
return b;
} else {
return fib(n - 1, b, a + b);
}
};
let n = 1;
while (true) {
yield fib(n++);
}
};
const fibsUnder4000000 = () => {
const arr = [];
for (let value of fibs()) {
if (value > 4000000) break;
arr.push(value);
}
return arr;
};
return fibsUnder4000000()
.filter(num => num % 2 === 0)
.reduce((sum = 0, fib) => sum + fib);
};
/**
* Problem 3
* The prime factors of 13195 are 5, 7, 13 and 29.
* What is the largest prime factor of the number 600851475143 ?
*/
const problem3 = () => {
return (() => {
const isMultiple = (n, div) => {
return n % div === 0;
};
const primeFactors = (n, candidate = 2, acc = []) => {
if (n <= 1) {
return [...acc].reverse();
} else if (isMultiple(n, candidate)) {
return primeFactors(n / candidate, candidate, [...acc, candidate]);
} else {
return primeFactors(n, candidate + 1, [...acc]);
}
};
return Math.max(...primeFactors(600851475143));
})();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment