Skip to content

Instantly share code, notes, and snippets.

@curtisharvey
Created July 27, 2010 05:35
Show Gist options
  • Save curtisharvey/491793 to your computer and use it in GitHub Desktop.
Save curtisharvey/491793 to your computer and use it in GitHub Desktop.
simple Collatz Conjecture in node
#! /usr/local/bin/node
var sys = require('sys'),
iter = [],
start = (process.argv.length > 2) ? parseInt(process.argv[2], 10) : null,
stdin;
function askForNumber() {
sys.print('enter a number: ');
if (stdin) {
stdin.resume();
} else {
stdin = process.openStdin();
stdin.setEncoding('utf8');
stdin.on('data', function(data) {
stdin.pause();
start = parseInt(data, 10);
if (isNaN(start)) {
sys.puts(data.trim() + ' is not a number');
askForNumber();
} else {
stdin.destroy();
collatz(start);
}
});
}
}
function collatz(n) {
iter[iter.length] = n;
if (n !== 1) {
n%2 ? collatz(3*n + 1) : collatz(n/2);
} else {
sys.puts('\n' + iter.join(' -> ') + '\n\n' + start + ' converged to 1 in ' + (iter.length - 1) + ' iterations');
}
}
if (!start || isNaN(start)) {
askForNumber();
} else {
collatz(start);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment