How can I set up the variables for this question?

Take any natural number n. 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. (This is called the Hailstone sequence).
Set the new number to n and repeat this process until n=1.
How many steps does it take for 71 to get to 1?
I'm a total idiot in Matlab in the real sense of the word. I have problem translating theories into practice. I need a leg up on understanding how I can apply concepts to solve this problem.

2 件のコメント

Walter Roberson
Walter Roberson 2013 年 9 月 5 日
cwc
cwc 2013 年 9 月 5 日
What is the best way to set up all the parameters? Is there some kind of mental process I must adopt? I can see all abstract reasoning very well but come problem solving mind just go blank!

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

 採用された回答

Image Analyst
Image Analyst 2013 年 9 月 5 日
編集済み: Image Analyst 2013 年 9 月 5 日

0 投票

I think you only need 2 variables, n and the number of steps you took. Use "n" because that's what they told you to use. Then pick a descriptive name for the other variable you need, like "numberOfSteps". Hints to get you started.
n = int32(42); % whatever.
numberOfSteps = int32(0);
while n ~= 1
if n is even, then % You do this
n = n/2
else
n = 3*n+1
end
numberOfSteps = ....... % You do this.
end
There's still some stuff in there for you to do, so good luck. By the way, that code is not that robust since there's no failsafe to prevent infinite loops, but I'll take your word on it that eventually you'll hit 1 as required.

1 件のコメント

cwc
cwc 2013 年 9 月 5 日
I shall work on it. Admittedly, I knew it involves loops and logical operators Just having problems condensing all the reasoning into syntax.

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

その他の回答 (1 件)

cwc
cwc 2013 年 9 月 6 日
編集済み: Image Analyst 2013 年 9 月 6 日

0 投票

function numberofsteps = naturalnumber(n)
numberofsteps = 0;
while n~=1;
if mod(n,2) == 0;
n = n/2;
else
n = 3*n + 1;
end
numberofsteps = numberofsteps + 1;
end

2 件のコメント

Image Analyst
Image Analyst 2013 年 9 月 6 日
Looks like it should work.
Walter Roberson
Walter Roberson 2013 年 9 月 6 日
Good thing that infinity is not a "natural number" ;-)
Still, I think the code will start misbehaving at about 2^51

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

カテゴリ

ヘルプ センター および 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