how to count the total number of recursion ?

5 ビュー (過去 30 日間)
Kratos
Kratos 2015 年 3 月 27 日
コメント済み: Andrew Newell 2015 年 3 月 27 日
Hello
I have a function
function [out num] = collatz(val)
num = 0;
if val == 1
out = 1;
elseif mod(val, 2) == 0
out = collatz(val/2);
else
out= collatz(3*val+1);
end
k = num + 1;
num = [num k]
end
For the number of counts, num I keep getting num = [0 1] How do I count the total number of recursion that occurs? I heard that we can make a helper function but I have no idea how to make one. Thank you.

採用された回答

Andrew Newell
Andrew Newell 2015 年 3 月 27 日
編集済み: Andrew Newell 2015 年 3 月 27 日
The problem is that you're not passing num to collatz, so how can it know how many times it has been called? Here is a version that makes num an optional argument, so you don't need to provide it in your call:
function [out, num] = collatz(val,varargin)
if nargin >1
num = varargin{1};
else
num = 0;
end
if val == 1
out = 1;
elseif mod(val, 2) == 0
[out,num] = collatz(val/2,num);
else
[out,num] = collatz(3*val+1,num);
end
num = num+1;
Now if you try
[out,num] = collatz(4)
you get
out =
1
num =
3
  2 件のコメント
Kratos
Kratos 2015 年 3 月 27 日
編集済み: Kratos 2015 年 3 月 27 日
thanks for the help, but the .p soln file that was provided gives num of 2. Similarly when I do [out3 num3] = collatz(5) I get
out = 1 and num = 6
but the num is supposed to 5.
Thanks.
Andrew Newell
Andrew Newell 2015 年 3 月 27 日
They must be defining it differently than I am. Just replace
num = 0;
by
num = -1;

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by