How to fix my recursive function?
17 ビュー (過去 30 日間)
古いコメントを表示
Write a recursive function mostFactors(a,b,fact) that does the following:
1. Takes as an input 3 positive integers.
2. Of the two integers a and b, the function returns the integer that has the most factors fact.
3. If both integers a and b have the same amount of factors fact, the function will return the larger integer.
4. Can not use the factor shortcut
Test your function with the following:
>> result=moreFactors(24,32,3)
result = 24
(24 = 3^1 · 2^3 , 32 = 2^5 )
My code:
function moreFactors(a,b,fact)
result=;
if(mod(a,fact)==0 && mod(b,fact)==0)
result=moreFactors(a/fact,b/fact,fact)*fact;
elseif(mod(a,fact)==0)
result=a;
elseif(mod(b,fact)==0)
result=b;
else
if(a>b)
result=a;
else
result=b;
end
end
end
0 件のコメント
採用された回答
Stephen23
2018 年 11 月 4 日
編集済み: Stephen23
2018 年 11 月 4 日
function out = moreFactors(a,b,fact)
ixa = fix(a)==a; % test if integer.
ixb = fix(b)==b; % test if integer.
if ixa && ixb
out = moreFactors(a/fact,b/fact,fact)*fact;
elseif ixa && ~ixb
out = a;
elseif ~ixa && ixb
out = b;
else
out = max(a,b);
end
>> moreFactors(24,32,3)
ans = 24
>> moreFactors(32,24,3)
ans = 24
>> moreFactors(80,168,2)
ans = 80
>> moreFactors(100,50,5)
ans = 100
0 件のコメント
その他の回答 (1 件)
madhan ravi
2018 年 11 月 4 日
編集済み: madhan ravi
2018 年 11 月 4 日
a=6 ; %EDITED
b=48;
result=morefact(a,b) %function calling
function result=morefact(a,b)
aa=unique(factor(a));
bb=unique(factor(b));
[~,m]=size(aa);
[~,n]=size(bb);
A=max(aa);
B=max(bb);
if m>n
result = a;
elseif n>m
result = b;
elseif m==n
if A>B
result = A;
else
result = B;
end
end
end
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Numeric Types についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!