Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update collatz.js #67

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 22 additions & 26 deletions algorithms/math/collatz.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,27 @@
/* Collatz conjecture */
"use strict";

function collatz(n) {
var numbers = []
/**known Collatz infinite loops*/
const CYCLES = new Set([
1, 0, -1, -5, -17, NaN, Infinity, -Infinity
]);

while (n > 1) {
numbers.push(n)
if (n % 2 === 0) {
n = n / 2;
} else {
n = (3 * n) + 1;
}
/**
* Collatz conjecture calculator.
* returns an array containing the Hailstone sequence of `n`.
* @param {number} n "seed"
*/
const collatz = n => {
const sequence = [];

while ( !CYCLES.has(n) ) {
sequence.push(n);
n = n % 2 === 0 ? n / 2 : 3 * n + 1;
}
numbers.push(n)
return numbers
sequence.push(n);
return sequence;
}

console.log(
'Collatz conjecture for n = 11',
collatz(11)
)

console.log(
'Collatz conjecture for n = 27',
collatz(27)
)

console.log(
'Collatz conjecture for n = 51',
collatz(51)
)
[11, 27, 51, -7].forEach(n => console.log(
`Hailstone sequence of ${n}`,
collatz(n)
));