***Python
Hailstones, also known as the Collatz sequence, are a mathematical curiosity. For any number in the sequence, the next number in the sequence is determined by two simple rules:
If the current number n is odd, the next number in the sequence is equal to 3 * n + 1
If the current number n is even instead, the next number in the sequence is equal to one half of n (i.e., n divided by 2)
We repeat this process until it produces 1 (which is where the "mathematical curiosity" comes into play; so far, mathematicians have been unable to prove that this process always (eventually) produces the value 1, but no one has been able to find a counterexample that doesn't eventually reach 1). A Hailstone sequence can begin with any positive integer. For example, the integer 6 produces the hailstone sequence
6, 3, 10, 5, 16, 8, 4, 2, 1
In the code cell below, use the input() command to read in an integer from the user (assume that this integer is always positive and greater than 1). Then use a loop (we recommend a while loop) and any extra variables that you may need to follow the rules above to generate a Hailstone sequence from your starting number. DO NOT print out the Hailstone numbers that you generate; instead, your code should print exactly one number when it finishes: the total number of values in the Hailstone sequence that you generated (including both the starting value and the final 1 that ends the sequence).
Helpful Hint: One easy way to check whether an integer is even or odd is to use the modulus operator. If the number modulo 2 produces 0 as its remainder, then that number is even; if the remainder is 1, then the number is odd. For example, 7 % 2 returns 1, indicating that 7 is odd.
Examples
The starting value 2 produces the output 2 (internally, it generates the sequence 2, 1).
The starting value 17 produces the output 13 (internally, it generates the sequence 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1).
****This is the full question
Program Code Screenshot :
Sample Output :
Program Code to Copy
#Read an integer
n = int(input())
c = 1
#Loop until number is not 1
while n!=1:
#Check if even or odd
if n%2==0:
n=n//2
else:
n = 3*n+1
c=c+1
print('Total number of values in the sequence ',c)
Get Answers For Free
Most questions answered within 1 hours.