How to fix my recursive function?

19 Ansichten (letzte 30 Tage)
michael story
michael story am 4 Nov. 2018
Bearbeitet: Stephen23 am 4 Nov. 2018
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

Akzeptierte Antwort

Stephen23
Stephen23 am 4 Nov. 2018
Bearbeitet: Stephen23 am 4 Nov. 2018
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

Weitere Antworten (1)

madhan ravi
madhan ravi am 4 Nov. 2018
Bearbeitet: madhan ravi am 4 Nov. 2018
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

Kategorien

Mehr zu Numeric Types finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by