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

HELP WITH MATLAB SCRIPT Activity 2: A Loop with a Conditional Now that you’ve go

ID: 2268568 • Letter: H

Question

HELP WITH MATLAB SCRIPT

Activity 2: A Loop with a Conditional

Now that you’ve gotten your my_factorial function working, let’s tie together several of the items we’ve discussed over the past few weeks.

Remember the Hailstone sequence? Well, now we know enough to write a program to compute the Hailstone path length for any (acceptable) number.

Here’s the pseudocode from lesson 4:

Procedure hailstone-path-length Inputs: n (integer)

Outputs: l (integer)

l = 1

while n > 1

if n is even then

n = n / 2

else n = 3 * n + 1

l = l + 1

return l // the length of the path

Now it’s your turn. Write a function which computes the Hailstone path length of a positive integer.

It is conjectured that all positive integers eventually reach 1 after repeated application of the Hailstone function. 5 Although the conjecture is believed to be true, it has not yet been proven. An example Hailstone path for 12 is

12 -> 6 -> 3 ->10 -> 5 -> 16 -> 8 -> 4 ->-> 2-> 1

In this case, the path length is 10. The while loop executes 9 times

Explanation / Answer

function length=hailstonepathlength(intiger)
% This function is used to find the hailstone path length of a positive
% intiger. where intiger is the input to which we have to find the
% hailstone path length. output is the length of the hailstone path of the
% input untiger.
n=intiger;
l=1; % Initiating the length with 1
while n>1 % checking wether the intiger is greater than 1 or not
  
if rem(n,2)==0; % If the intiger is even (the remainder should be zero
n=n/2;
else n=3*n+1; % Checking the condition for odd
end
l=l+1;
end
length=l; % Finally the length of the Hailstone path of the input