+ 2
Find the gcd of two numbers by recursion?
Recursion
4 Respostas
+ 17
So let GCD of two numbers be, for example:
GCD (36, 8)
= GCD (8, 36 % 8) = GCD (8, 4)
= GCD (4, 8 % 4 ) = 4
wherein we can see that 8 % 4 = 0, GCD = 4.
Try to see behind the pattern of the formula, then it would be easy to code it in recursive form.
+ 2
long gcd (long x, long y){
if (x%y==0)
return y;
return gcd (y, x%y);
}
+ 1
Your answers forget one important thing: If the first input is smaller, you need to reorder.
+ 1
That can be handled at the time function call in main (). Still thanks for pointing it out