Help on my function script?
9 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
michael story
il 25 Set 2018
Modificato: Fangjun Jiang
il 25 Set 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 Commenti
Risposta accettata
Fangjun Jiang
il 25 Set 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 Commento
Fangjun Jiang
il 25 Set 2018
Modificato: Fangjun Jiang
il 25 Set 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
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!