English, asked by gourig1410, 10 months ago

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.

Answers

Answered by daud2281
2

Answer:

#include <iostream>

using namespace std;

int main ()

{

   int ans,a,b;

   std::cin >> ans;

   a=ans/2;

   b=ans;

   std::cout<<ans<<"\n";

   while ( ans != 1 )

   {

       if ( ans % 2 == 1)

           ans = (3 * ans) + 1;

       else

           ans /= 2;

   

   std::cout << ans << "\n";

   }

 if (b==1)

 {

   cout<<b-1;

 }

 else if(b==3)

 {

   cout<<b*2+1;

 }

 else if (a<b)

 {

   cout<<b+2;

 }

 

   return 0;

}

Explanation:

,might help u...but test case not complete.

Answered by one536948
0

Answer:

I have the answer in java:

import java.util.*;

class Main

{

 public static void main(String args[])

 {

   //Try out your code here

   Scanner sc = new Scanner(System.in);

   int n = sc.nextInt();

   System.out.println(n);

   int count = 0;

   while(n != 1) {

     count++;

    if(n%2==0) {

      n /= 2;

      System.out.println(n);

    } else {

      n = 3*n + 1;

      System.out.println(n);

    }

   }

   System.out.println(count);

 }

}

Explanation:

Similar questions