Skip to content

Instantly share code, notes, and snippets.

@ParkinT
Created August 12, 2012 16:44
Show Gist options
  • Save ParkinT/3332796 to your computer and use it in GitHub Desktop.
Save ParkinT/3332796 to your computer and use it in GitHub Desktop.
Random Number generator using Collatz Conjecture

When I first uncovered Collatz conjecture it made perfect sense to me. You are simply dividing an even number in half until you reach one and, if the number is not even you coerce it to be so.

This created a flash of inspiration for me to devise this simple routine.

{This could be used as the basis of a program to prove the "unsolved problem" of whether Collatz conjecture applies to ALL numbers greater than one.}

# Take an input "seed" as the starting whole number, apply the Collatz conjecture - counting each iteration - until you reach 1. Your result is the value of the iteration counter
#This program halts when the sequence reaches 1, in order to avoid printing an endless cycle of 4, 2, 1. If the Collatz conjecture is true, the program will always halt (stop) no matter what positive starting integer is given to it.
def hailstone(n)
p = 0
while n > 1 do
p +=1
n = 3*n + 1 if !(n % 2)
n = (n * 0.5).to_i if (n % 2)
end
p
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment