How to fix my recursive function?

22 次查看(过去 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

采纳的回答

Stephen23
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
And tested using the examples here:
>> moreFactors(24,32,3)
ans = 24
>> moreFactors(32,24,3)
ans = 24
>> moreFactors(80,168,2)
ans = 80
>> moreFactors(100,50,5)
ans = 100

更多回答(1 个)

madhan ravi
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

类别

Help CenterFile Exchange 中查找有关 Numeric Types 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by