Respuesta :
Answer:
- #include <iostream>
- using namespace std;
- int hailstoneLength(int n){
- int term = 1;
- while(n != 1){
- if(n % 2 == 0){
- n = n / 2;
- term++;
- }
- else{
- n = n * 3 + 1;
- term++;
- }
- }
- return term;
- }
- int main()
- {
- cout<<hailstoneLength(8);
- return 0;
- }
Explanation:
Hailstone sequence is a list of number that is generated by following the rules as below:
- Given a starting number (e.g. 5)
- If the number is even, divide it by 2
- If the number is odd, multiply it by 3 and then add 1
- 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