Please follow the insturctions and solve it by C++ ASAP.
The hailstone sequence is a series of numbers that can be generated with an algorithm that takes an input number n. The sequence is defined as:
If n is 1, the sequence stops.
If n is even, the next number is n / 2.
If n is odd, the next number is 3n + 1.
For example, if we start with n = 10, the sequence is:
10, 5, 16, 8, 4, 2, 1
This sequence is interesting because it appears that given any number, the sequence will always reach 1 (and stop). Unfortunately, some numbers take many steps to reach 1.
Write a recursive function that prints out each step of the hailstone sequence given n, but also accepts an parameter to limit the number of steps to some value. Only the function is needed (don't write an accompanying main()).
ANSWER:-
#include <iostream>
using namespace std;
void HailstoneNumbers(int N,int s)
{
cout << N << " ";
if (N == 1 || s==1) {
return;
}
else if (N % 2 == 0) {
// If N is Even.
HailstoneNumbers(N / 2,s-1);
}
else if (N % 2 != 0) {
// N is Odd.
HailstoneNumbers(3 * N + 1,s-1);
}
}
// Driver function
int main()
{
int N,s;
cout<<"Enter a number : ";
cin>>N;
cout<<"Enter the maximum number of steps : ";
cin>>s;
cout<<"the sequence is: ";
HailstoneNumbers(N,s);
return 0;
}
// OUTPUT
// If any doubt please comment
Get Answers For Free
Most questions answered within 1 hours.