#Day3- #100DaysChallenge- Matlab Loops| Collatz Sequence
#Day3-Collatz Sequence
Task: Generate a Collatz Sequence for the given n
Collatz Sequence:
If the given number is even then the next number in the sequence will be n/2.If the given number is odd the next number in the sequence is 3n+1. This procedure has to be followed until we reach 1
Example:n=12
c={12}
12 is even then next entry will be 12/2=6
c={12,6}
6 is even then next entry will be 6/2=3
c={12,6,3}
3 is odd then next entry will be 3*3+1=10
c={12,6,3,10}
10 is even then next entry will be 10/2=5
c={12,6,3,10,5}
5 is odd then next entry will be 5*3+1=16
c={12,6,3,10,5,16}
16 is even then next entry will be 16/2=8;
c={12,6,3,10,5,16,8}
8 is even then next entry will be 8/2=4;
c={12,6,3,10,5,16,8,4}
4 is even then next entry will be 4/2=2;
c={12,6,3,10,5,16,8,4,2}
2 is even then next entry will be 2/2=1;
c={12,6,3,10,5,16,8,4,2,1}
Matlab Code:
function c = collatz(n)
inc=1;
c(inc)=n;
while n>1
if mod(n,2)==0
n=n/2;
inc=inc+1;
c(inc)=n;
else
n=3*n+1;
inc=inc+1;
c(inc)=n;
end
end
end
Sample Input and Output:
c=collatz(15)
c =
Columns 1 through 12
15 46 23 70 35 106 53 160 80 40 20 10
Columns 13 through 18
5 16 8 4 2 1
c=collatz(78)
c =
Columns 1 through 12
78 39 118 59 178 89 268 134 67 202 101 304
Columns 13 through 24
152 76 38 19 58 29 88 44 22 11 34 17
Columns 25 through 36
52 26 13 40 20 10 5 16 8 4 2 1
Click here for Code Explanation
No comments