This small library helps to calculate Collatz sequences with nodejs. Using the big-integer nodejs library this computations can be donde for arbitrary large numbers (examples see below).
git clone https://github.com/osick/Collatz
cd Collatz
npm install
cd examples
nodejs example.js
Collatz sequences nk are defined for k>=0 as follows:
- Choose an initial number n0>1
- For k>=0
- if nk is even then nk+1=nk/2
- else nk+1=3*nk+1
For example choose n0 = 7 then
n1 = 22
n2 = 11
...
n14 = 8
n15 = 4
n16 = 2
n17 = 1
n18 = 4
n19 = 2
n20 = 1
n12 = 4 ...
The Collatz Conjecture now is that for any initial number n0 there is a k>0 s.t. nk = 1. This conjecture is still open for more than 60 years. For more information see the Wikipedia on Collatz Conjecture .
var Collatz = require('collatz.js').Collatz;
// integer input is supported
var collatz = new Collatz(17);
collatz.init();
// big-integer is supported
var collatz_2 = new Collatz(bigInt(2).pow(5000).add(1));
collatz_2.init();
// strings of digits are supported, e.g.
var collatz_3 = new Collatz("612736124162374123874373678123461782346187293461782347823645");
collatz_3.init();
Set the initial number
var collatz = new Collatz("17");
collatz.number("12");
// 12 is the initial number
Returns the initial number
var collatz = new Collatz("17");
collatz.number("12");
console.log(collatz.number());
// Output "12"
Returns the initial number, synonymous to number()
var collatz = new Collatz("17");
console.log(collatz.toString());
// Output string "17"
Return the length of the Collatz sequence until reaching 1
collatz.number("17");
console.log(collatz.length());
//Output 12
Return the stopping time
collatz.number("17");
console.log(collatz.stoppingTime());
//Output 3
Return the Collatz sequence starting from the initial value
collatz.number("17");
var seq=collatz.sequence();
console.log(seq.toString());
//returns [52,26,13,40,20,10,5,16,8,4,2,1,52,26,13,40,20,10,5,16,8,4,2,1,52,26,13,40,20,10,5,16,8,4,2,1]
Iterator to set the class to the next Collatz number in the sequence
collatz.number("17");
console.log(collatz.iterate().toString());
//prints "52"
Checks if the current value is "1"
collatz.number("17");
while(!collatz.isOne()){
console.log(collatz.iterate().toString()+", ");
}
//prints out "52, 26, 13, ...., 1"
Return an array of lengths m starting from the initial and with stepsize s
collatz.number("17");
console.log(collatz.lengths(20,1).toString());
//Output string "0,20,7,7,15,15,10,23,10,111,18,18,18,106,5,26,13,13,21,21"
Return an array of stopping times m starting from the initial and with stepsize s
collatz.number("17");
console.log(collatz.stoppingTimes(30,2).toString());
//Output string "6,3,8,3,96,3,91,3,6,3,13,3,8,3,88"
- big-integer NodeJS module