Help on my function script?

9 Ansichten (letzte 30 Tage)
michael story
michael story am 25 Sep. 2018
Bearbeitet: Fangjun Jiang am 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

Akzeptierte Antwort

Fangjun Jiang
Fangjun Jiang am 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 Kommentar
Fangjun Jiang
Fangjun Jiang am 25 Sep. 2018
Bearbeitet: Fangjun Jiang am 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by