How to fix my recursive function?
조회 수: 19 (최근 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!