Skip to content

Instantly share code, notes, and snippets.

@paceaux paceaux/collatz.js
Last active Mar 29, 2019

Embed
What would you like to do?
Math Buddies
function collatz(n, steps = []) {
if (isNaN(n)) return NaN;
if (steps.length === 0) steps.push(n);
const isEven = n%2 === 0;
const newInt = isEven ? n / 2 : (3 * n) + 1;
steps.push(newInt);
return newInt !== 1 ? collatz(newInt, steps) : steps;
}
Math.collatz = collatz;
function factorial(n) {
if (isNaN(n)) return NaN;
let result = n;
while (n > 1) result = result * --n;
return result;
}
Math.factorial = factorial;
function format (n, separator = ',') {
if (isNaN(n) ) return NaN;
const nString = n.toString();
const nCommas = [...nString].reverse().reduceRight((acc, cur, idx) => {
const needsSeparator = (idx + 1)%3 === 0 && (idx + 1 < nString.length);
return `${acc}${needsSeparator ? separator : '' }${cur}`;
}, '');
return nCommas;
}
Math.format = format;
function isEven(n) {
return n % 2 === 0
}
function isPerfectSquare(n) {
return Math.ceil(Math.sqrt(n)) === Math.sqrt(n)
}
function getRangeOfTestables(n) {
const range = [];
let rangeCounter = 0;
/* don't need get range from 0 to [n]:
once you get to (n / 3) + 1, it's not possible for [n] to be a multiple of that number:
Take range of integers from 0-53: [3,5,7,11,13,15,17,19,21,23,27,29,31,33,35,37,39,41,43,45,47,49,51]
3 * 17 == 51
3* 19 == 57
BTW: could filter just the first _third_ of prime numbers, instead. But Recursion slows this down
*/
while (rangeCounter++ < Math.ceil(n / 3)) {
if (!isEven(rangeCounter) && !isPerfectSquare(rangeCounter)) range.push(rangeCounter);
}
/*
Don't need last el of the range because lastEl * firstEl == n
*/
return range.slice(0, range.length - 1);
}
function isPrime(n) {
// return early if it doesn't meet easy-to-recognize criteria for being prime
if (isNaN(n) || isEven(n) || isPerfectSquare(n)) return false;
let isPrime = true;
const rangeOfTestables = getRangeOfTestables(n);
for (let int of rangeOfTestables) {
if (n % int === 0) {
isPrime = false;
break;
}
}
return isPrime;
}
Math.isPrime = isPrime;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.