The length of a hailstone sequence is the number of terms it contains. For example, the hailstone sequence in example 1 (5, 16, 8, 4, 2, 1) has a length of 6 and the hailstone sequence in example 2 (8, 4, 2, 1) has a length of 4. Write the method hailstoneLength(int n), which returns the length of the hailstone sequence that starts with n.

Respuesta :

Answer:

  1. #include <iostream>
  2. using namespace std;
  3. int hailstoneLength(int n){
  4.    int term = 1;
  5.    while(n != 1){
  6.        if(n % 2 == 0){
  7.            n = n / 2;
  8.            term++;
  9.        }
  10.        else{
  11.            n = n * 3 + 1;
  12.            term++;
  13.        }
  14.    }
  15.    return term;
  16. }
  17. int main()
  18. {
  19.    cout<<hailstoneLength(8);
  20.    return 0;
  21. }

Explanation:

Hailstone sequence is a list of number that is generated by following the rules as below:

  1. Given a starting number (e.g. 5)
  2. If the number is even, divide it by 2
  3. If the number is odd, multiply it by 3 and then add 1
  4. the starting number will either be repeatedly divided or multiplied until the final n reaches 1

So, we can create a function called hailstoneLength that takes one input number, n, as starting number (Line 4).

In the function initialize the variable term with value of 1 (Line 5).  Create a while loop and set the condition to enable the loop running until the n become 1 (Line 6). In the loop, keep checking the n value if it is currently even or odd using modulus operator (Line 7 - 14). If it is even, divide n by 2 and increment the term by one (Line 7 - 10). If it is odd, multiple it by 3 and add 1 (Line 11 - 14). At last, return term value as output (Line 16).

In the main program, test the function by passing 8 as argument. We shall get the output of 4 (Line 21).  

The program is an illustration of methods.

Methods are program blocks that are executed when called or evoked

The hailstoneLength method in Python, where comments are used to explain each line is as follows:

#This defines the method

def hailstoneLength(n):

   #This initializes the number of terms to 1

   term = 1

   #This is repeated while n is not 1

   while(n != 1):

       #If n is even

       if(n % 2 == 0):

           #This divides n by 2

           n = n / 2

       #Otherwise, if n is odd

       else:

           #This increases the product of n by 1

           n = n * 3 + 1

       #This increases the term by 1

       term+=1

   #This returns the term

   return term

Read more about methods at:

https://brainly.com/question/15683939