Write a recursive method that calculates the length of the c

Write a recursive method that calculates the length of the collatz sequence for a given input.
The collatz sequence for an input may be calculated as follows. If the current value is even, the next value is that number divided by two (n/2). If the current value is odd, the next value is that number multiplied by three and then incremented (3n+1). This process continues until the next value is 1
For input = 3 the collatz sequence would be {3,10,5,16,8,4,2,1}.
Only positive inputs (greater than 1) will be given!

collatz(3) returns 8.

Solution

#include<stdio.h>
#include<iostream.h>
#include<conio.h>
int count=1;// global variable
int collatz(int );// declaration of a method
int main(){
int n;
  
cout<<\"enter input\";// take input from user on which you want to call collatz method.
cin>>n;

int length= collatz(n);// catch the length returned by the collatz method in length variable
cout<<\"The length of collatz sequence :\";
cout<<length; // display the length
getch();
return 0;
}
int collatz(int n){// definition of recursive method collatz
  
if(n>1){
if(n%2==0){ //if input is even , then call recursive mrthod on n/2
count++;
n=n/2;

collatz(n);
  
}else{// if input is odd , then call recursive mrthod on 3n+1

count++;
n=3*n+1;
  
collatz(n);
}}
return count;
  
  
}

Write a recursive method that calculates the length of the collatz sequence for a given input. The collatz sequence for an input may be calculated as follows. I

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site