Hailstones – Python

# -*- coding: utf-8 -*-
Created on Thu Sep 15 23:41:45 2016

@author: Shruti

#Iteration with while: using while, write a function which takes one argument,
#an integer n, and calculates the Hailstones sequence starting at n.
#If you don't know the Hailstones sequence:
#if hihi is even, then hi+1=hi/2hi+1=hi/2 ; but if hihi is odd,
#then hi+1=3hi+1hi+1=3hi+1 .
#The sequence will repeat when it reaches the subsequence 4, 2, 1, 4, …… ,
#so your loop should stop when it hits 1

import math

def hailstones(x):
 while x > 1:
 print("%d" %x)
 if(x%2 == 0):
 x = x/2
 print("%d" %x)
 elif(x%2 != 0):
 x = 3*x + 1
 print("%d" %x)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: