フィルターのクリア

How can I solve this odd/even loop question (hailstone sequence)?

17 ビュー (過去 30 日間)
mrs_matlab_rookie_thanks
mrs_matlab_rookie_thanks 2015 年 9 月 22 日
編集済み: Walter Roberson 2015 年 9 月 22 日
n = 71
If n is even, divide it by 2 to get n / 2.
If n is odd, multiply it by 3 and add 1 to obtain 3n + 1.
Repeat process until n = 1.
I need to find out how many steps it takes to reach 1..
thanks!
  2 件のコメント
Thorsten
Thorsten 2015 年 9 月 22 日
What have you tried so far? Where did you got stuck?
mrs_matlab_rookie_thanks
mrs_matlab_rookie_thanks 2015 年 9 月 22 日
ok, so im really new to matlab, but this is what i tried doing:
n(1,1) = 71;
iterations(1,1) = 0;
ii=1;
while n(1,ii)==1;
if mod(n(1,ii),2)==1
(3*n(1,ii))+1;
else n(1,ii)/2;
ii=ii+1;
end
iterations(1,ii) = iterations(1,ii) + 1;
end

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

採用された回答

Varun Pai
Varun Pai 2015 年 9 月 22 日
I think this is your requiremnt. Please check
num = 71;
count = 0;
while(num~=1)
count = count+1;
if(mod(num,2)==0)
num = num/2;
else
num = 3*num + 1;
end
end
fprintf('count = %d', count);

その他の回答 (1 件)

Thorsten
Thorsten 2015 年 9 月 22 日
First you can skip the 1, and just write n(ii).
Next you have forgotten to assign the new value, and you have to move the increment of ii outside the else-clause
if mod(n(ii),2)==1
n(ii+1) = 3*n(ii)+1;
else
n(ii+1) = n(ii)/2;
end
ii=ii+1;
Finally you have to change the while loop condition; while n(ii) == 1 means that the loops only continues if the n is 1, but it should continue if n is NOT 1.

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by