All bout Yoan Ante and everything he finds interesting

Archive for October, 2012

Collatz Conjecture written python executable from the web.

I wrote this little gem for the Collatz Conjecture about a month back when I first read about it and want to try it out for myself but didn’t want to try it with paper and pencil. The Collatz Conjecture states. If you take any natural number (zero to infinity) n. If n is even, divide it by 2 to get n / 2. If n is odd, multiply it by 3 and add 1 to obtain 3n + 1. If you repeat the process enough times you will always end with a result of 1. Here is the program written in Codeskulptor so you can run it from your web browser. 


Here is the code:

#Collatz conjecture fun

import random
#init x
x = 0
#gen random integer to disect with Motherfucking Collatz
x = random.randint(1000,150000)
print (“Randomly printing a number between 1000 tp 150,000”)
print (“the number to we are going mess with is”, x)

#First test of even odd and printing remainder
#If remainder is 1 x is odd if 0 x is even
remainder = x %2
print remainder

#Set counter to display number of iterations program
#executed to complete.
counter = 0

#loop that will itirate until x finally becomes 1
while x > 1:
#increment counter by 1
counter += 1
#test odd eveness
remainder = x%2
#execute if even
if remainder == 0:
x = (x/2)
print (“the number is even divide by 2”, x)
#excute if odd
elif remainder == 1:
x = (x*3) + 1
print (“the number is odd multiply by 3 add 1” , x)

#exit comment
print (“This problem took “,counter, “iterations to complete”)
input (“Press the enter key to exit”)