Help on my function script?
9 views (last 30 days)
Show older comments
michael story
on 25 Sep 2018
Edited: Fangjun Jiang
on 25 Sep 2018
My function is [s,m]=collatz(the input number) which I used x=input('Enter a natural number:'). If I want an even input to be divided by 2, and an odd input to be multiplied by 3 plus 1. This goes on as long as the number is greater than one. Ex: starting with 3 it would give 3-10-5-16-8-4-2-1. How would I set this up?
function[s,m]=collatz()
x=input('Enter a natural number:')
while mod(x,2)==0 %shows x(natural number) is even
x=x/2
if mod(x,2)==1 %shows x(natural number) is odd
x=x*3+1
end
end
0 Comments
Accepted Answer
Fangjun Jiang
on 25 Sep 2018
almost there
while x>1
if mod(x,2)==0 %shows x(natural number) is even
x=x/2
elseif mod(x,2)==1 %shows x(natural number) is odd
x=x*3+1
end
end
1 Comment
Fangjun Jiang
on 25 Sep 2018
Edited: Fangjun Jiang
on 25 Sep 2018
to prevent infinite loop when the input is a decimal number, for example 3.2, modify it as below
x=input('Enter a natural number:');
while x>1
if mod(x,2)==0 %shows x(natural number) is even
x=x/2
elseif mod(x,2)==1 %shows x(natural number) is odd
x=x*3+1
else
x
break;
end
end
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!