Impact-Site-Verification: dbe48ff9-4514-40fe-8cc0-70131430799e

Search This Blog

Mathematical beauty "Collatz sequence" in MATLAB

A Collatz sequence is the sequence where, for a given number n, the next number in the sequence is either n/2 if the number is even or 3n+1 if the number is odd. The sequence always terminates with 1.

For more detail , check the below link:

https://en.wikipedia.org/wiki/Collatz_conjecture

Sample input:

13

Sample output:

[13 40 20 10 5 16 8 4 2 1]

Code:

clc
x=input('Enter the number:');
m=x;
Y=[];
Y=[Y m];
while(m>1)
    if(rem(m,2)==0)
        m=m/2;
        Y=[Y m];
    else
        m=3*m+1;
        Y=[Y m];
    end
end 
disp(Y)

OUTPUT:




Explanation:


    

No comments

Popular Posts

Followers