Collatz problem
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.
Answers
Answer:
#include<iostream>
using namespace std;
int main()
{
int n,c=0;
cin>>n;
cout<<n<<"\n";
while(n!=1)
{
if(n%2==0)
{
n=n/2;
cout<<n<<"\n";
c++;
}
else
{
n=(3*n)+1;
cout<<n<<"\n";
c++;
}
}
cout<<c;
}
Explanation:
Answer:
#include<stdio.h>
int main(){
int n = 11;
while(n > 1){
if(n % 2 == 0){ //for even numbers
n = n / 2;
printf("%d\n", n);
}
else{ //for odd numbers
n = n * 3 + 1;
printf("%d\n", n);
}
}
return 0;
}
Explanation:
Let’s understand this with an example.
Assuming that n is 11:
Since 11 is odd, the second number in the sequence is 3 * 11 + 1 = 34
3∗11+1=34
, i.e., 3n=1
Now we have [11, 34,…]
Since 34 is even, the next number is 34 / 2 = 17
34/2=17
, i.e., n/2
Now we have [11, 34, 17…]
17 is odd,
#spj3