Q. The hailstone sequence starting at a positive integer n is generated by following two simple rules. If n even, the next number in the sequence is n/ 2. If n is odd, the next number in the sequence is 3*n+1 Repeating this process, the hailstone sequence gets generated. Write a recursive function hailstone ( n) Which prints the hailstone sequence beginning at 1. Stop when the sequence reaches the number 1 (since otherwise, we would loop forever 1, 4, 2, 1, 4, 2, ….).


You can understand by Watching video :-



Answer =

def hailstone( n ) :
    if n == 1 :
        return 1
    elif n % 2 == 0 :
        print( int(n ) , end=" , ")
        return hailstone( n / 2 ) 
    else :
        print( int(n ) , end=" , ")
        return hailstone( 3 * n + 1) 


n = int(input("Enter a number : "))
print ( hailstone( n ) )

Output :-

Enter a number : 85
85 , 256 , 128 , 64 , 32 , 16 , 8 , 4 , 2 , 1

>>> 

Enter a number : 100
100 , 50 , 25 , 76 , 38 , 19 , 58 , 29 , 88 , 44 , 22 , 11 , 34 , 17 , 52 , 26 , 13 , 40 , 20 , 10 , 5 , 16 , 8 , 4 , 2 , 1

>>> 

Enter a number : 99
99 , 298 , 149 , 448 , 224 , 112 , 56 , 28 , 14 , 7 , 22 , 11 , 34 , 17 , 52 , 26 , 13 , 40 , 20 , 10 , 5 , 16 , 8 , 4 , 2 , 1

>>>






Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post