Skip to content

Instantly share code, notes, and snippets.

@ShinNoNoir
Created April 28, 2020 05:34
Show Gist options
  • Save ShinNoNoir/8c4a7ad755490fe27c69fec20a61bdb4 to your computer and use it in GitHub Desktop.
Save ShinNoNoir/8c4a7ad755490fe27c69fec20a61bdb4 to your computer and use it in GitHub Desktop.
Project Euler 14
// Project Euler 14, but in JS (longest Collatz chain for starting n < 1e6)
// Take a cup of ☕, this is going to take a while... (because it's slow)
function* collatzSeq(n) {
yield n;
if (n<=1) return;
yield* collatzSeq(n%2==0 ? n/2 : 3*n+1);
}
function seqLength(s) {
let i=0;
for (const _ of s) ++i;
return i;
}
function* range(start, end) {
for (let i=start; i != end; yield(i++));
}
function* map(s, f) {
for (const x of s) yield f(x);
}
function maxBy(s, by) {
let maxValue = Number.MIN_VALUE;
let res = undefined;
for (const x of s) {
const cmpValue = by(x);
if (cmpValue > maxValue) {
maxValue = cmpValue;
res = x;
}
}
return res;
}
let [length, n] = maxBy(map(range(1,1000000), n => [seqLength(collatzSeq(n)), n]), x=>x[0])
console.log(`seqLength(collatzSeq(${n})) == ${length}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment