Write a Program to Find GCD of Two Numbers
What is GCD (Greatest Common Divisor)?
GCD of the two numbers is the largest positive integer that divides both numbers.
- The GCD of the two numbers is always lesser than two numbers or equal to the smaller number.
- GCD of two numbers can never be greater than both numbers.
- GCD of the two prime numbers is one.
- GCD of the 10 and 5 is 5 (As 10 is divisible by 5.)
- GCD of the 90 and 48 is 6.
Program to Find the GCD of Two Numbers
There are many interviews where this question has been asked. This has been asked in Kirloskar Technical interview round.
Here we are using recursion.
- Divide the number ‘a’ by ‘b’ and get the reminder.
- If the remainder is zero (the number ‘a’ is divisible by the number ‘b’), return ‘b’ (GCD of the two numbers is ‘b’).
- Else, assign a=b and b=a%b. Call step 1 recursively.
def gcd(a, b): if a%b==0: return b return gcd(b, a%b) print(gcd(8, 6)) print(gcd(45, 12)) print(gcd(120, 46))
2 3 24
This small function can be very much handy for solving Python competitive coding questions.
This is the simplest solution and program to find GCD of two numbers.