How Do I Create/Fix My Code For Collatz Conjecture Using A For Or While Loop?
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
John D'Errico
2018-7-2
编辑:John D'Errico
2018-7-2
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!