Skip to content

Instantly share code, notes, and snippets.

@DanielFGray
Last active February 26, 2016 05:49
Show Gist options
  • Save DanielFGray/bd21df831ef6bcc34016 to your computer and use it in GitHub Desktop.
Save DanielFGray/bd21df831ef6bcc34016 to your computer and use it in GitHub Desktop.
collatz conjecture
#!/usr/bin/env node
'use strict';
const range = function(start, stop) {
return Array.apply(null, { length: 1 + stop - start })
.map((v, i) => start + i);
};
const collatz = function(n, len) {
let steps = [];
while(n != 1) {
// if n is even, divide by 2
// if n is odd, multiply by 3 and add 1
n = (n % 2 === 0)
? n / 2
: 3 * n + 1;
steps.push(n);
}
return (typeof len === 'undefined')
? steps
: steps.length;
}
// console.log(range(1, 100).map( e => collatz(e)));
// module.exports = {'range': range, 'collatz': collatz};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment