Problem 21. Return the 3n+1 sequence for n
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.
So if
n = 13
then
c = [13 40 20 10 5 16 8 4 2 1]
Solution Stats
Problem Comments
-
6 Comments
Show
3 older comments
Cedric
on 5 Apr 2013
Hep, Cody Team, could you remove my solution please?
Cedric
on 8 Apr 2013
Thank you!
Mandeep Singh
on 14 Jun 2013
nice one but consumes size dunno how to reduce it
jubin soni
on 13 Nov 2016
a bit tricky but nice
Pascal Wenger
on 17 Feb 2017
I like this problem, because I learnt about the Collatz sequence story. Very interessting.
Anant
on 23 Mar 2024 at 9:23
function c = collatz(n)
c(1) = n;
while (1>0)
if (n == 1)
c(end+1) = n;
break
elseif (mod(n,2) == 0)
c(end+1) = n;
n = n/2;
collatz(n);
else
c(end+1) = n;
n = 3*n + 1;
collatz(n);
end
end
c(1) = [];
end
This solution is correct as I ran the Test Cases myself. But the compiler timed out. What should I do ?
Solution Comments
Show comments
Problem Recent Solvers8033
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!