Skip to Main Content
Blog

Calculate GCD of two numbers in Python

Calculate GCD of two numbers in Python

Enter a: 48
Enter b: 18
GCD: 6
from math import gcd


def main():
	"""
	Calculates the greatest common divisor of two numbers.
	"""

	a = int(input("Enter a: "))
	b = int(input("Enter b: "))
	d = gcd(a, b)
	print(d)


if __name__ == "__main__":
	main()

Recursive GCD calculation

def main():
	"""
	Prints the greatest common divisor of two numbers.
	"""

	a = int(input("Enter a: "))
	b = int(input("Enter b: "))

	d = gcd(a, b)
	print(d)


def gcd(a: int, b: int) -> int:
	"""
	Calculates the greatest common divisor of two numbers using recursion.
	"""

	return a if b == 0 else gcd(b, a % b)


if __name__ == "__main__":
	main()