Douglas Hofstadter's Pulitzer-prize-winning book, Gödel, Escher, Bach, poses the following mathematical puzzle:
- Pick a positive integer n as the start.
- If n is even, divide it by 2.
- If n is odd, multiply it by 3 and add 1.
- Continue this process until n is 1.
The number n will travel up and down but eventually end at 1 (at least for all numbers that have ever been tried -- nobody has ever proved that the sequence will terminate). Analogously, hailstone travels up and down in the atmosphere before eventually landing on earth.
The sequence of values of n is often called a Hailstone sequence, because hailstones also travel up and down in the atmosphere before falling to earth.
Does it make sense to implement using recursion? I wrote some bad solution below. Please correct me.
def hailstone(n):
if(n<0):
print("Invalid input")
return
if(n==1):
print(1)
return
if(n%2 == 0):
print(n)
hailstone(n/2)
return
if(n%2==1):
print(n)
hailstone((n*3) + 1)
return
How do I move the n<0
condition to the right place?
if(n<0):
would be? – jonrsharpe Jul 8 at 7:38