Inspired by http://xkcd.com/710/ here is a code golf for it.
The Challenge
Given a positive integer greater than 0, print out the hailstone sequence for that number.
The Hailstone Sequence
See Wikipedia for more detail..
- If the number is even, divide it by two.
- If the number is odd, triple it and add one.
Repeat this with the number produced until it reaches 1. (if it continues after 1, it will go in an infinite loop of 1 -> 4 -> 2 -> 1...
)
Sometimes code is the best way to explain, so here is some from Wikipedia
function collatz(n)
show n
if n > 1
if n is odd
call collatz(3n + 1)
else
call collatz(n / 2)
This code works, but I am adding on an extra challenge. The program must not be vulnerable to stack overflows. So it must either use iteration or tail recursion.
Also, bonus points for if it can calculate big numbers and the language does not already have it implemented. (or if you reimplement big number support using fixed-length integers)
Test case
Number: 21
Results: 21 -> 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1
Number: 3
Results: 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
Also, the code golf must include full user input and output.
bc 41 chars
I guess this kind of problems is what
bc
was invented for:Test:
Proper code:
bc
handles numbers with up toINT_MAX
digitsEdit: The Wikipedia article mentions this conjecture has been checked for all values up to 20x258 (aprox. 5.76e18). This program:
tests 220,000+1 (aprox. 3.98e6,020) in 68 seconds, 144,404 cycles.
C#: 216 Characters
in long form:
New Version, accepts one number as input provided through the command line, no input validation.
173154 characters.in long form:
I am able to shave a few characters by ripping off the idea in this answer to use a for loop rather than a while. 150 characters.
Python -
95645146 charObviously does not produce a stack overflow.
x86 assembly, 1337 characters
LOLCODE: 406 CHARAKTERZ
TESTD UNDR JUSTIN J. MEZA'S INTERPRETR. KTHXBYE!
not the shortest, but an elegant clojure solution