Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Given any positive integer n , the hailstone sequence starting at n is obtained

ID: 3663521 • Letter: G

Question

Given any positive integer n, the hailstone sequence starting at n is obtained as follows. You write a sequence of numbers, one after another. Start by writing n. If n is even, then the next number is n/2. If n is odd, then the next number is 3n + 1. Continue in this way until you write the number 1.

For example, if you start at 7, then the next number is 22 (3 × 7 + 1). The next number after 22 is 11. The hailstone sequence starting at 7 is
  [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
and it contains 17 numbers. The hailstone sequence starting at 6 is [6, 3, 10, 5, 16, 8, 4, 2, 1], and the hailstone sequence starting at 1 is [1].

Write a C++ program that reads a number n from the user (after giving a suitable prompt) and then tells the user the following information:

the entire hailstone sequence starting at n, all on one line, with the numbers separated by spaces; the length of the hailstone sequence that starts with n; the largest number in the hailstone sequence that starts with n; the largest length of any hailstone sequence starting with a number from 1 to n. the starting number of the longest hailstone sequence starting with a number from 1 to n.

The output needs to be sensible and easy to read, not just numbers. Each piece of information should be on a separate line. For example, a session with this program might look as follows. Parts in black are written by the program. Parts in blue are typed by the user.

Explanation / Answer

#include <iostream>
using namespace std;


int nextNo(int iNum)
{

if(iNum % 2 == 0) //if number is even
{
iNum /= 2;
}

else //if number is odd
{
iNum = iNum * 3 + 1;
}
return iNum;
}

void nextNoLoop() //prints the hailstone sequence starting at n on one line, separating the numbers by spaces
{
while(iNum!=1)
{
nextNo(int x);
}

}
  



int main()
{
int iNum;
cout << "What number shall I start with? ";
cin >> iNum;
cout << "The hailstone sequence starting at " << iNum << " is " << endl;
cout << nextNoLoop(nextNo(iNum));
system("PAUSE");
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote