In this post we will be discussing about the Collatz sequence and how to obtain such sequence by writing the code in C++.Basically Collatz sequence is obtain by the following steps, if number is odd then multiply by 3 and add 1 to it, again when it becomes even divide it by 2 and the same procedure is followed until we get 1 i.e., the final number of the sequence.
Problem Description :
The rules for generating Collatz sequence are: If n is even: n = n / 2 If n is odd: n = 3n + 1 For example, if the starting number is 5 the sequence is : 5 -> 16 -> 8 -> 4 -> 2 -> 1. It has been proved for almost all integers, that the repeated application of the above rule will result in a sequence that ends in 1. Now, write a C++ program to generate the Collatz sequence.
INPUT & OUTPUT FORMAT:
The input is an integer 'n' which denotes the first term of the sequence.
As output, print the numbers in the sequence and also print the number of times the rule has to be applied in order to reach 1.
Logic to follow to come-up with the solution :
1.Declare the required sets of variables to use.
2.Take the input number from the user keyboard.
3.Assign the input number to a declared variable and initialize the count to 0 (i.e. c=0).
4.Now apply the loop with the condition that will follow until we get the number 1
5.if inputted number is odd then follow (3*n+1) and if even then follow (n / 2).
6. In the next step increment the count value to get the count value of the numbers in the sequence.
7.Finally print the required series and the count value.
Let’s write the required code for the problem :
Sample Test Cases have been passed successfully
You can run same set of code at this portal, click here to go to the online portal and just give required set of inputs and click on Execute to run the program.
If you liked this post, then share this with your friends and if anything is confusing or incorrect then let me know in the comment section.
Thanks from my side, this is Mayank, keep learning and exploring !!