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

matlab Code The Collatz conjecture is a conjecture in mathematics that concerns

ID: 2291247 • Letter: M

Question

matlab Code

The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows Start with any positive integer n. Then each term is obtained from the previous term as follows: If the previous term is even, the next term is one half the previous term. . If the previous term is odd, the next term is 3 times the previous term plus 1 The conjecture is that no matter what value of n, the sequence will always reach 1. For instance, starting with n=12, one gets the sequence 12, 6, 3, 10, 5, 16, 84, 2, 1 Write a MATLAB script which asks the user to provide a positive integer number (call it n). If n is not a positive integer, the program should stop and return an appropriate error message using error command in MATLAB. If the input is valid, create the sequence starting with n and print the numbers on the screen until the sequence reaches 1 and stops. Run your program for n=12 and report the outcome.

Explanation / Answer

Prompt='enter a number'; n=input(prompt);

s=[ ];

If( n<=0) 'invalid input' ; exit;

While(n>=1)

s=[s n];

m=mod(n,2);

if(m==0)

n=n/2;

else n=3*n+1;

end

end

s