How to fix my recursive function?

19 visualizaciones (últimos 30 días)
michael story
michael story el 4 de Nov. de 2018
Editada: Stephen23 el 4 de Nov. de 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

Respuesta aceptada

Stephen23
Stephen23 el 4 de Nov. de 2018
Editada: Stephen23 el 4 de Nov. de 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

Más respuestas (1)

madhan ravi
madhan ravi el 4 de Nov. de 2018
Editada: madhan ravi el 4 de Nov. de 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

Categorías

Más información sobre Numeric Types en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by