Greatest Common Divisor, Recursive code

조회 수: 9 (최근 30일)
Kitt Naughton
Kitt Naughton 2020년 2월 22일
편집: Walter Roberson 2024년 8월 21일
Hello,
This code uses recursion to find the GCD of two numbers that are inputed. The code works but for some reason GCD is being assigned to 0 at the end. The test case I am using sets greatestCommonDivisor(10007,500).
Any help is greatly appreciated
The code is as follows:
function GCD = greatestCommonDivisor(a, b)
if(a > b)
temp1 = a;
temp2 = b;
else
temp1 = b;
temp2 = a;
end
if temp1 == 0
GCD = temp2;
return
elseif temp2 == 0
GCD = temp1;
return
else
r = rem(temp1, temp2);
end
if(r == 0)
disp(temp2)
if(temp2 == 1)
GCD = 1;
disp(GCD)
return
else
GCD = temp2;
return
end
else
greatestCommonDivisor(temp2, r);
end
end
  댓글 수: 1
Jalaj Gambhir
Jalaj Gambhir 2020년 2월 25일
Hi,
I do not see where GCD is assigned to 0, can you provide more clarifications/ output screenshot or something? Works fine for me, with GCD = 1 at the end.

댓글을 달려면 로그인하십시오.

답변 (1개)

Deepak
Deepak 2024년 8월 21일
Hi @Kitt Naughton, To my understanding, you have written code to calculate GCD of two integers.
Your code works fine, but the GCD variable is being assigned to 0 at the end.
To resolve this issue, when calling the recursive method “greatestCommonDivisor(temp2, r)” at the end, you need to assign the return value to the output variable GCD.
GCD = greatestCommonDivisor(temp2, r);
It is important to assign the result of a recursive call to a variable so that the result can be returned up the call stack.
By assigning “GCD = greatestCommonDivisor(b, r)” you capture this result and ensure it is returned correctly.
Here is the updated MATLAB code:
function GCD = greatestCommonDivisor(a, b)
if(a > b)
temp1 = a;
temp2 = b;
else
temp1 = b;
temp2 = a;
end
if temp1 == 0
GCD = temp2;
return
elseif temp2 == 0
GCD = temp1;
return
else
r = rem(temp1, temp2);
end
if(r == 0)
disp(temp2)
if(temp2 == 1)
GCD = 1;
disp(GCD)
return
else
GCD = temp2;
return
end
else
GCD = greatestCommonDivisor(temp2, r);
disp(GCD);
end
end
I hope this helps.

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by