A random number generator is as per logic below.
Suppose we select some initial number X and then build the sequence of values by the following rules:
if X is even i.e. X modulo 2 = 0) then
Xnext = X / 2
else
Xnext = 3 * X + 1
1.e. if X is odd, sequence grows - and if it is even, sequence decreases.
For example, with X = 15 we have sequence:
15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
After the sequence reaches 1 it enters the loop 1 421 421....
The intrigue is in the fact that any starting number X gives the sequence which sooner or later reaches 1.
Your task is for given numbers to calculate how many steps are necessary to come to 1.
Pro
Input data value for which calculations should be performed. Answer the count of steps for getting Sequence to 1.
Input format
A positive integer
Output format
Number of steps required to reach 1
Answers
Answered by
0
Answer:
10
Explanation:
THIS WILL HELP US SO MUCH
Answered by
0
Answer:
#include <iostream>
using namespace std;
int main() {
int x,xi,c=1;
cout<<"\nEnter the initial number: ";
cin>>x;
while(x!=1)
{
if(x%2==0)
{
xi=x/2;
c++;
x=xi;
}
else
{
xi=(3*x)+1;
c++;
x=xi;
}
}
cout<<"\nThe number of steps required to reach 1 is "<<c;
return 0;
}
Explanation:
- Declare variables to store the initial number, the next terms in the sequence, and to keep a count of the steps.
- Take the initial number as the input from the user.
- Check whether the number is even or odd using the modulo operator.
- If the number is even, the next term is half the previous term. The counter is incremented.
- If the number is odd, the next term is one greater than three times the previous term. The counter is incremented.
- Steps 3 to 5 are repeated until the term becomes equal to one.
- Once the term is equal to one, the loop is terminated.
- The number of steps is printed as the output.
#SPJ3
Similar questions