Find the gcd of two numbers by recursion? | Sololearn: Learn to code for FREE!
+ 2

Find the gcd of two numbers by recursion?

Recursion

21st Mar 2017, 4:01 PM
_$ubha$h_ iitd
_$ubha$h_ iitd - avatar
4 ответов
+ 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.
21st Mar 2017, 4:05 PM
Hatsy Rei
Hatsy Rei - avatar
+ 2
long gcd (long x, long y){ if (x%y==0) return y; return gcd (y, x%y); }
21st Mar 2017, 4:08 PM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar
+ 1
Your answers forget one important thing: If the first input is smaller, you need to reorder.
23rd Mar 2017, 6:15 AM
1of3
1of3 - avatar
+ 1
That can be handled at the time function call in main (). Still thanks for pointing it out
23rd Mar 2017, 11:20 AM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar