How to find gcd of two numbers | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to find gcd of two numbers

How to get idea

3rd Feb 2020, 6:11 PM
spider
13 Answers
+ 2
You can use the euclidian algorithm: gcd(12,10) 12 % 10 = 2 10 % 2 = 0 -> mod returns 0 -> gcd(12,10) = 2 gcd(14,9) 14 % 9 = 5 9 % 5 = 4 5 % 4 = 1 4 % 1 = 0 -> mod returns 0 gcd(14,9) = 1 gcd(20,5) 20 % 5 = 0 gcd(20,5) = 5
3rd Feb 2020, 6:29 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
a way to do it in pyhton: def gcd(a, b): while a != b: if a > b: a -= b else: b -= a return a
3rd Feb 2020, 6:58 PM
Anton Böhler
Anton Böhler - avatar
+ 2
Perhaps it is not so easy to find that in so long code there, so the solution here in C# (can be implemented very well in any other language): int Gteil(int a, int b) { int rest = a % b; if (rest == 0) return b; else return Gteil(b, rest); }
3rd Feb 2020, 7:58 PM
JaScript
JaScript - avatar
+ 2
Ideas for calculation gcd can be found in the math books of a high school.
5th Feb 2020, 4:03 PM
JaScript
JaScript - avatar
+ 1
Ex: for 10,12 10: divisors are 1,2,5,10 12: divisors are 1,2,3,4,6,12 GCD(10,12) The greatest common divisor is 2. Since common divisors are 1,2. Greater is 2. Find common divisors, pick greater one..
3rd Feb 2020, 6:16 PM
Jayakrishna 🇮🇳
+ 1
I want a general case for a,b
3rd Feb 2020, 6:36 PM
spider
+ 1
K.Srujan Kumar Please don't ask for codes here. We gave you two alternatives how you can solve the problem. You only need to convert it into a code. I am sure you can do it. :)
3rd Feb 2020, 6:42 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Okk tnq
3rd Feb 2020, 6:43 PM
spider
+ 1
K.Srujan Kumar If you need help with your code please show us your attemp.
3rd Feb 2020, 6:49 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
If you like a possible solution can be found here: https://code.sololearn.com/cEv41IqV7eYc/?ref=app Have lots of fun with it!
3rd Feb 2020, 6:52 PM
JaScript
JaScript - avatar
- 1
Plzz
3rd Feb 2020, 6:36 PM
spider
- 1
Print the program plzzz
3rd Feb 2020, 6:36 PM
spider