Skip to content
January 17, 2011 / gus3

Just One More

I know I said I was going to leave the Collatz sequence tinkering, but I did want to try one more thing: really, really huge numbers. Fortunately, most Unix/Linux installations come with “bc” and “dc” for just such occasions. The following function for bc returns the Collatz distance for a given number (no argument validation):

define collatz(c) {
	if (c % 2 == 0) {
		return collatz(c / 2) + 1;
	} else {
		if (c > 1) {
			return collatz(c * 3 + 1) + 1;
		} else {
			return 0;
		}
	}
}

To try it out, copy it into an empty text file, then save as “collatz.b” in your home directory. You can then type “bc ~/collatz.b” in a command shell to launch bc and load the new Collatz function. Simply type “collatz(10^600)” to find out that the Collatz distance of 10600 is 10,441.

I doubt there’s a CPU that can handle such large numbers natively. My wimpy netbook, with its 630MHz Celeron-M, calculates it in 0.83 seconds, using a little over a meg and a half of RAM at its peak.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: