Saturday, March 27, 2010

Colletz

XKCD brings my attention to a mathematical conjecture called the Collatz Conjecture that claims that for a particular operation, all numbers have a chain that eventually leads back to one. Read the Wikipedia article for details.While a definite proof would win one a cool $500, computer verification only suggests that the claim is true. No proof has actually been written. Mathematical proofs via computer are beyond me, but I did, for practice, write a verifying program, as they are very very short. Mine is 32 lines long, written in C.#include <stdio.h>void collatz(int);int main(int argc, char *argv[]){ if(argc==2) { int num=argv[1]; collatz(num); } else { printf("USAGE: collatz number\n"); } return 0;}void collatz(int num){ int count=0; while(num!=1) { if(num%2==0) { num=num/2; } else { num=num*3+1; } count++; } printf("Returned to 1 after %d cycles.\n",count);}

The program accepts one number from you, the user, and runs a collatz chain until it reaches one. It then reports the length of this chain.A trivial change to the main would produce a program that would report the length of ALL integers until it overflowed:int main(){ int num; for(num=0;num<MAX_INT;num++) { printf("%d:",num); collatz(num); } return 0;}

The variable MAX_INT would be preset with a #define command according to the nature of the computer. Mine would be 2^64, as integers are 64-bits long on my computer.

Google Analytics

Google is monitoring this blog, and giving me a regular report on it. Isn't that neat?

Privacy Policy

We use third-party advertising companies to serve ads when you visit our website. These companies may use information (not including your name, address, email address, or telephone number) about your visits to this and other websites in order to provide advertisements about goods and services of interest to you. If you would like more information about this practice and to know your choices about not having this information used by these companies, click here.