Movatterモバイル変換


[0]ホーム

URL:


Open In App

Given two numbers a and b, the task is to find their greatest common divisor (GCD), which is the largest number that divides both a and b completely.For example:

Input: a = 10, b = 15 ->Output: 5
Input: a = 31, b = 2 ->Output: 1

Let’s explore different methods to find the GCD in Python.

Using math.gcd()

The math module provides a built-in gcd() function that internally implements the optimized Euclidean algorithm. This is the most efficient and pythonic way to find the GCD.

Python
importmatha,b=10,15print("GCD is",math.gcd(a,b))

Output
GCD is 5

Explanation: math.gcd(a, b) directly returns the greatest common divisor of the two numbers.

Using Iterative Euclidean Algorithm

This approach repeatedly replaces the larger number with the remainder until one becomes zero. The non-zero number left is the GCD.

Python
a,b=10,15whileb:a,b=b,a%bprint("GCD is",a)

Output
GCD is 5

Explanation:

  • The loop continues until b becomes zero.
  • In each iteration, a is replaced with b, and b with a % b.
  • Once b is zero, a holds the GCD.

Using Recursive Euclidean Algorithm

This is the traditional recursive form of the algorithm. It calls itself repeatedly by swapping a and b % a until a becomes zero.

Python
defgcd(a,b):ifa==0:returnbreturngcd(b%a,a)a,b=10,15print("GCD is",gcd(a,b))

Output
GCD is 5

Explanation:

  • The function keeps calling itself with the remainder until the base case (a == 0) is reached.
  • The value of b at that point is the greatest common divisor.

Using Subtraction-based Euclidean Algorithm

This method repeatedly subtracts the smaller number from the larger until both become equal.

Python
a,b=10,15whilea!=b:ifa>b:a-=belse:b-=aprint("GCD is",a)

Output
GCD is 5

Explanation:

  • The larger number is reduced by the smaller in each step.
  • When both numbers become equal, that value is the GCD.

Please refer complete article onBasic and Extended Euclidean algorithms for more details!


Improve
Improve
Article Tags :

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp