How Do I Create/Fix My Code For Collatz Conjecture Using A For Or While Loop?
3 views (last 30 days)
Show older comments
Hi, I am working on a project for school and am attempting to create code for Collatz Conjecture using a for or while loop. Attached is my code that I have created so far, but I am getting too many errors I can't fix, and some help would be nice. Thanks in advance.
assume(x > 0)
if mod(n, 2) == 0
n = n/2
else
n = 3*n+1
end
if n = 1
% break?
end
0 Comments
Answers (1)
John D'Errico
on 2 Jul 2018
Edited: John D'Errico
on 2 Jul 2018
I'm not sure what assume(x>0) has to do with anything, because you are working with the variable n.
But why have you not just put a while loop around it? For example, this seems to work:
while n ~= 1
if mod(n,2) == 0
n = n/2
else
n = 3*n+1
end
end
Note that you CANNOT use a test like
if n=1
because n=1 is an assignment operator, NOT a test for equality. It is not necessary anyway, since you just want that test in the while statement anyway. I'm not sure what you intend to do with the sequence produced. Your code will just dump it to the command window.
Oh, learn to use semicolons on your lines. But I suppose if your goal is to just dump n into the command window, then it works perfectly well.
What you need to decide is what you want out of this loop. Do you just want to count how many iterations it takes until the iterations land at 1? That is a fairly common goal, to count the iterations, since the Collatz conjecture is that all sequences will eventually terminate there. Or, you can store all the iterations for any given sequence. But only you know what you want to do here.
1 Comment
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!