Question: C++ Problem Statement Take a number, n . If n is even, divide it by 2. If odd, multiply by 3 and add 1. Repeat
C++
Problem Statement
Take a number, n. If n is even, divide it by 2. If odd, multiply by 3 and add 1. Repeat with the new number, forever or until you get the number 1. For instance, suppose you start with the number 3:
- Since 3 is odd, you multiply by 3 and add 1 to get 9 + 1 = 10.
- Since 10 is even, you divide by 2 to get 5.
- Since 5 is odd, you multiply by 3 and add 1 to get 16.
- Since 16 is a power of 2, you will repeatedly divide by 2, getting 8, 4, 2, and 1 in that order.
The sequence of numbers produced by this procedure is known as a hailstone sequence. The hailstone sequence beginning with 3 is therefore "3 10 5 16 8 4 2 1". The Collatz conjecture, proposed by Lothar Collatz in 1937, is that the hailstone sequence for any starting number always terminates; that is, it always reaches 1. This conjecture is unproven at this time, but is easy to verify for small n.
Your task for this lab is to produce the hailstone sequence for an arbitrary starting value. You are given an int value n, and asked to return a string containing the hailstone sequence beginning at n. The string should contain each number in the sequence in order, separated by single spaces. There should be no leading or trailing spaces.
Constraints
- The input n will be between 1 and 100, inclusive.
Examples
-
1 Returns: "1"
-
2 Returns: "2 1"
-
3 Returns: "3 10 5 16 8 4 2 1"
-
7 Returns: "7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1"
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
