Help on my function script?

9 ビュー (過去 30 日間)
michael story
michael story 2018 年 9 月 25 日
編集済み: Fangjun Jiang 2018 年 9 月 25 日
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

採用された回答

Fangjun Jiang
Fangjun Jiang 2018 年 9 月 25 日
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 件のコメント
Fangjun Jiang
Fangjun Jiang 2018 年 9 月 25 日
編集済み: Fangjun Jiang 2018 年 9 月 25 日
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

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by