Program for COLLATZ SEQUENCE in C++

COLLATZ SEQUENCE

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.

Program for COLLATZ SEQUENCE in C++

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.

SAMPLE INPUT:

5

SAMPLE OUTPUT:

5

16

8

4

2

1

5

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

                                         (i.e., while(n!=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.

                                             (i.e., c++)

7.Finally print the required series and the count value.

Let’s write the required code for the problem :

Code :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<iostream>
using namespace std;
int main()
{

  int n,c=0;

 cin>>n;

  while(n!=1)

  {

   cout<<n<<"\n";

   if(n%2!=0)

     n=n*3+1;

   else

     n=n/2

 c++;

 }

/* Printing the sequence*/

   cout<<n<<"\n";

/* Printing the count value of numbers */ 

   cout<<c;

   return 0;

 }


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 !!

Next Post Previous Post
No Comment
Add Comment
comment url

Best Buy Products