Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Stein's Algorithm for finding GCD
Next article icon

Euclidean algorithms (Basic and Extended)

Last Updated : 17 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

The Euclidean algorithm is a way to find the greatest common divisor of two positive integers. GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common prime factors.

Examples:

input: a = 12, b = 20
Output: 4
Explanation: The Common factors of (12, 20) are 1, 2, and 4 and greatest is 4.

input: a = 18, b = 33
Output: 3
Explanation: The Common factors of (18, 33) are 1 and 3 and greatest is 3.

GCD

Table of Content

  • Basic Euclidean Algorithm for GCD
  • Extended Euclidean Algorithm
  • How does Extended Algorithm Work? 
  • How is Extended Algorithm Useful? 

Basic Euclidean Algorithm for GCD

The algorithm is based on the below facts. 

  • If we subtract a smaller number from a larger one (we reduce a larger number), GCD doesn't change. So if we keep subtracting repeatedly the larger of two, we end up with GCD.
  • Now instead of subtraction, if we divide the larger number, the algorithm stops when we find the remainder 0.
CPP
// C++ program to demonstrate working of  // extended Euclidean Algorithm  #include <bits/stdc++.h>  using namespace std;  // Function to return // gcd of a and b int findGCD(int a, int b) {     if (a == 0)         return b;     return findGCD(b % a, a); }  int main()  {      int a = 35, b = 15;     int g = findGCD(a, b);      cout << g << endl;     return 0;  } 
C
// C program to demonstrate working of  // extended Euclidean Algorithm  #include <stdio.h>  // Function to return // gcd of a and b int findGCD(int a, int b) {     if (a == 0)         return b;     return findGCD(b % a, a); }  int main() {      int a = 35, b = 15;     int g = findGCD(a, b);      printf("%d\n", g);     return 0;  } 
Java
// Java program to demonstrate working of  // extended Euclidean Algorithm  class GFG {      // Function to return     // gcd of a and b     static int findGCD(int a, int b) {         if (a == 0)             return b;         return findGCD(b % a, a);     }      public static void main(String[] args) {          int a = 35, b = 15;         int g = findGCD(a, b);          System.out.println(g);     } } 
Python
# Python program to demonstrate working of  # extended Euclidean Algorithm   # Function to return # gcd of a and b def findGCD(a, b):     if a == 0:         return b     return findGCD(b % a, a)  # Main function def main():     a, b = 35, 15     g = findGCD(a, b)     print(g)  if __name__ == "__main__":     main() 
C#
// C# program to demonstrate working of  // extended Euclidean Algorithm  using System;  class GFG {      // Function to return     // gcd of a and b     static int FindGCD(int a, int b) {         if (a == 0)             return b;         return FindGCD(b % a, a);     }      public static void Main() {          int a = 35, b = 15;         int g = FindGCD(a, b);          Console.WriteLine(g);     } } 
JavaScript
// JavaScript program to demonstrate working of  // extended Euclidean Algorithm   // Function to return // gcd of a and b function findGCD(a, b) {     if (a === 0)         return b;     return findGCD(b % a, a); }  function main() {      let a = 35, b = 15;     let g = findGCD(a, b);     console.log(g); }  // Run the main function main(); 

Output
GCD(10, 15) = 5 GCD(35, 10) = 5 GCD(31, 2) = 1

Time Complexity: O(log min(a, b))
Auxiliary Space: O(log (min(a,b)))

Extended Euclidean Algorithm

 Extended Euclidean algorithm also finds integer coefficients x and y such that: ax + by = gcd(a, b) 

Examples:  

Input: a = 30, b = 20
Output: gcd = 10, x = 1, y = -1
Explanation: 30*1 + 20*(-1) = 10

Input: a = 35, b = 15
Output: gcd = 5, x = 1, y = -2
Explanation: 35*1 + 15*(-2) = 5

The extended Euclidean algorithm updates the results of gcd(a, b) using the results calculated by the recursive call gcd(b%a, a). Let values of x and y calculated by the recursive call be x1 and y1. x and y are updated using the below expressions. 

ax + by = gcd(a, b)
gcd(a, b) = gcd(b%a, a)
gcd(b%a, a) = (b%a)x1 + ay1
ax + by = (b%a)x1 + ay1
ax + by = (b - [b/a] * a)x1 + ay1
ax + by = a(y1 - [b/a] * x1) + bx1

Comparing LHS and RHS,
x = y1 - \lfloor b/a \rfloor* x1
 y = x1

C++
// C++ program to demonstrate working of  // extended Euclidean Algorithm  #include <bits/stdc++.h>  using namespace std;  // Function for extended Euclidean Algorithm  int gcdExtended(int a, int b, int &x, int &y) {      // Base Case      if (a == 0)  {          x = 0;          y = 1;          return b;      }       int x1, y1;      int gcd = gcdExtended(b%a, a, x1, y1);       // Update x and y using results of      // recursive call      x = y1 - (b/a) * x1;      y = x1;      return gcd;  }   int findGCD(int a, int b) {      int x = 1, y = 1;     return gcdExtended(a, b, x, y); }  int main()  {      int a = 35, b = 15;     int g = findGCD(a, b);      cout << g << endl;     return 0;  }  
C
// C program to demonstrate working of  // extended Euclidean Algorithm  #include <stdio.h>  // Function for extended Euclidean Algorithm  int gcdExtended(int a, int b, int *x, int *y) {      // Base Case      if (a == 0) {          *x = 0;          *y = 1;          return b;      }       int x1, y1;      int gcd = gcdExtended(b % a, a, &x1, &y1);       // Update x and y using results of      // recursive call      *x = y1 - (b / a) * x1;      *y = x1;      return gcd;  }   int findGCD(int a, int b) {      int x = 1, y = 1;     return gcdExtended(a, b, &x, &y); }  int main() {      int a = 35, b = 15;     int g = findGCD(a, b);      printf("%d\n", g);     return 0;  } 
Java
// Java program to demonstrate working of  // extended Euclidean Algorithm  class GFG {      // Function for extended Euclidean Algorithm      static int gcdExtended(int a, int b, int[] x, int[] y) {          // Base Case          if (a == 0) {              x[0] = 0;              y[0] = 1;              return b;          }           int[] x1 = {0}, y1 = {0};          int gcd = gcdExtended(b % a, a, x1, y1);           // Update x and y using results of          // recursive call          x[0] = y1[0] - (b / a) * x1[0];          y[0] = x1[0];          return gcd;      }       static int findGCD(int a, int b) {         int[] x = {1}, y = {1};         return gcdExtended(a, b, x, y);     }      public static void main(String[] args) {          int a = 35, b = 15;         int g = findGCD(a, b);          System.out.println(g);     } } 
Python
# Python program to demonstrate working of  # extended Euclidean Algorithm   # Function for extended Euclidean Algorithm  def gcdExtended(a, b, x, y):      # Base Case      if a == 0:          x[0] = 0         y[0] = 1         return b       x1, y1 = [0], [0]     gcd = gcdExtended(b % a, a, x1, y1)      # Update x and y using results of      # recursive call      x[0] = y1[0] - (b // a) * x1[0]      y[0] = x1[0]      return gcd   def findGCD(a, b):     x, y = [1], [1]     return gcdExtended(a, b, x, y)  # Main function def main():     a, b = 35, 15     g = findGCD(a, b)     print(g)  if __name__ == "__main__":     main() 
C#
// C# program to demonstrate working of  // extended Euclidean Algorithm  using System;  class GFG {      // Function for extended Euclidean Algorithm      static int GcdExtended(int a, int b, ref int x, ref int y) {          // Base Case          if (a == 0) {              x = 0;              y = 1;              return b;          }           int x1 = 0, y1 = 0;          int gcd = GcdExtended(b % a, a, ref x1, ref y1);           // Update x and y using results of          // recursive call          x = y1 - (b / a) * x1;          y = x1;          return gcd;      }       static int FindGCD(int a, int b) {         int x = 1, y = 1;         return GcdExtended(a, b, ref x, ref y);     }      public static void Main() {          int a = 35, b = 15;         int g = FindGCD(a, b);          Console.WriteLine(g);     } } 
JavaScript
// JavaScript program to demonstrate working of  // extended Euclidean Algorithm   // Function for extended Euclidean Algorithm  function gcdExtended(a, b, x, y) {      // Base Case      if (a === 0) {          x[0] = 0;          y[0] = 1;          return b;      }       let x1 = [0], y1 = [0];      let gcd = gcdExtended(b % a, a, x1, y1);       // Update x and y using results of      // recursive call      x[0] = y1[0] - Math.floor(b / a) * x1[0];      y[0] = x1[0];      return gcd;  }   function findGCD(a, b) {     let x = [1], y = [1];     return gcdExtended(a, b, x, y); }  // Main function function main() {     let a = 35, b = 15;     let g = findGCD(a, b);     console.log(g); }  // Run the main function main(); 

Output
5 

Time Complexity: O(log min(a, b))
Auxiliary Space: O(log (min(a,b)))

How does Extended Algorithm Work? 

As seen above, x and y are results for inputs a and b,

a.x + b.y = gcd                      ----(1)  

And x1 and y1 are results for inputs b%a and a

(b%a).x1 + a.y1 = gcd   

When we put b%a = (b - (\lfloor b/a \rfloor).a) in above, 
we get following. Note that \lfloor b/a\rfloor is floor(b/a)

(b - (\lfloor b/a \rfloor).a).x1 + a.y1  = gcd

Above equation can also be written as below

b.x1 + a.(y1 - (\lfloor b/a \rfloor).x1) = gcd      ---(2)

After comparing coefficients of 'a' and 'b' in (1) and 
(2), we get following, 
x = y1 - \lfloor b/a \rfloor * x1
y = x1

How is Extended Algorithm Useful? 

The extended Euclidean algorithm is particularly useful when a and b are coprime (or gcd is 1). Since x is the modular multiplicative inverse of "a modulo b", and y is the modular multiplicative inverse of "b modulo a". In particular, the computation of the modular multiplicative inverse is an essential step in RSA public-key encryption method.



Next Article
Stein's Algorithm for finding GCD

A

Ankur
Improve
Article Tags :
  • Mathematical
  • DSA
  • GCD-LCM
Practice Tags :
  • Mathematical

Similar Reads

    LCM of given array elements
    In this article, we will learn how to find the LCM of given array elements.Given an array of n numbers, find the LCM of it. Example:Input : {1, 2, 8, 3}Output : 24LCM of 1, 2, 8 and 3 is 24Input : {2, 7, 3, 9, 4}Output : 252Table of Content[Naive Approach] Iterative LCM Calculation - O(n * log(min(a
    14 min read
    GCD of more than two (or array) numbers
    Given an array arr[] of non-negative numbers, the task is to find GCD of all the array elements. In a previous post we find GCD of two number.Examples:Input: arr[] = [1, 2, 3]Output: 1Input: arr[] = [2, 4, 6, 8]Output: 2Using Recursive GCDThe GCD of three or more numbers equals the product of the pr
    11 min read
    Euler's Totient Function
    Given an integer n, find the value of Euler's Totient Function, denoted as Φ(n). The function Φ(n) represents the count of positive integers less than or equal to n that are relatively prime to n. Euler's Totient function Φ(n) for an input n is the count of numbers in {1, 2, 3, ..., n-1} that are re
    10 min read
    Euclidean algorithms (Basic and Extended)
    The Euclidean algorithm is a way to find the greatest common divisor of two positive integers. GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common prime factors.Examples:input: a = 12, b = 20Output: 4Explanatio
    9 min read
    Stein's Algorithm for finding GCD
    Stein's algorithm or binary GCD algorithm is an algorithm that computes the greatest common divisor of two non-negative integers. Stein’s algorithm replaces division with arithmetic shifts, comparisons, and subtraction.Examples: Input: a = 17, b = 34 Output : 17Input: a = 50, b = 49Output: 1Algorith
    14 min read
    Program to find LCM of two numbers
    Given two positive integers a and b. Find the Least Common Multiple (LCM) of a and b.LCM of two numbers is the smallest number which can be divided by both numbers. Input : a = 10, b = 5Output : 10Explanation : 10 is the smallest number divisible by both 10 and 5Input : a = 5, b = 11Output : 55Expla
    5 min read
    GCD, LCM and Distributive Property
    Given three integers x, y, z, the task is to compute the value of GCD(LCM(x,y), LCM(x,z)) where, GCD = Greatest Common Divisor, LCM = Least Common MultipleExamples: Input: x = 15, y = 20, z = 100Output: 60Explanation: The GCD of 15 and 20 is 5, and the LCM of 15 and 20 is 60, which is then multiplie
    4 min read
    Euler's Totient function for all numbers smaller than or equal to n
    Euler's Totient function ?(n) for an input n is the count of numbers in {1, 2, 3, ..., n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. For example, ?(4) = 2, ?(3) = 2 and ?(5) = 4. There are 2 numbers smaller or equal to 4 that are relatively pri
    13 min read
    Count number of pairs (A <= N, B <= N) such that gcd (A , B) is B
    Given a number n, we need to find the number of ordered pairs of a and b such gcd(a, b) is b itselfExamples : Input : n = 2Output : 3The pairs are (1, 1) (2, 2) and (2, 1) Input : n = 3Output : 5(1, 1) (2, 2) (3, 3) (2, 1) and (3, 1)[Naive Approach] Counting GCD Pairs by Divisor Propertygcd(a, b) =
    6 min read

    Problems on GCD

    Series with largest GCD and sum equals to n
    Given integers n and m, construct a strictly increasing sequence of m positive integers with sum exactly equal to n such that the GCD of the sequence is maximized. If multiple sequences have the same maximum GCD, return the lexicographically smallest one. If not possible, return -1.Examples : Input
    7 min read
    Program to find GCD of floating point numbers
    The greatest common divisor (GCD) of two or more numbers, which are not all zero, is the largest positive number that divides each of the numbers. Example: Input : 0.3, 0.9Output : 0.3Explanation: The GCD of 0.3 and 0.9 is 0.3 because both numbers share 0.3 as the largest common divisor.Input : 0.48
    4 min read
    Largest Subset with GCD 1
    Given n integers, we need to find size of the largest subset with GCD equal to 1. Input Constraint : n <= 10^5, A[i] <= 10^5Examples: Input : A = {2, 3, 5}Output : 3Explanation: The largest subset with a GCD greater than 1 is {2, 3, 5}, and the GCD of all the elements in the subset is 3.Input
    6 min read
    Summation of GCD of all the pairs up to n
    Given a number n, find sum of all GCDs that can be formed by selecting all the pairs from 1 to n. Examples: Input : n = 4Output : 7Explanation: Numbers from 1 to 4 are: 1, 2, 3, 4Result = gcd(1,2) + gcd(1,3) + gcd(1,4) + gcd(2,3) + gcd(2,4) + gcd(3,4) = 1 + 1 + 1 + 1 + 2 + 1 = 7Input : n = 12Output
    10 min read
    GCD of more than two (or array) numbers
    Given an array arr[] of non-negative numbers, the task is to find GCD of all the array elements. In a previous post we find GCD of two number.Examples:Input: arr[] = [1, 2, 3]Output: 1Input: arr[] = [2, 4, 6, 8]Output: 2Using Recursive GCDThe GCD of three or more numbers equals the product of the pr
    11 min read
    GCD of digits of a given number
    Given a number n, find GCD of its digits. Examples : Input : 345 Output : 1 GCD of 3, 4 and 5 is 1. Input : 2448 Output : 2 GCD of 2, 4, 4 and 8 is 2 We traverse the digits of number one by one using below loop digit = n mod 10; n = n / 10; While traversing digits, we keep track of current GCD and k
    4 min read
    Maximize GCD of all possible pairs from 1 to N
    Given an integer N (> 2), the task is to find the maximum GCD among all pairs possible by the integers in the range [1, N]. Example: Input: N = 5 Output: 2 Explanation : GCD(1, 2) : 1 GCD(1, 3) : 1 GCD(1, 4) : 1 GCD(1, 5) : 1 GCD(2, 3) : 1 GCD(2, 4) : 2 GCD(2, 5) : 1 GCD(3, 4) : 1 GCD(3, 5) : 1 G
    3 min read
    GCD of two numbers formed by n repeating x and y times
    Given three positive integer n, x, y. The task is to print Greatest Common Divisor of numbers formed by n repeating x times and number formed by n repeating y times. 0 <= n, x, y <= 1000000000.Examples : Input : n = 123, x = 2, y = 3. Output : 123 Number formed are 123123 and 123123123. Greate
    6 min read
    Program to find Greatest Common Divisor (GCD) of N strings
    Given an array of string arr[], the task is the Greatest Common Divisor of the given array of string. In strings 'A' and 'B', we say "B divides A" if and only if A = concatenation of B more than 1 times.Find the largest string which divides both A and B. Examples: Input: arr[] = { "GFGGFG", "GFGGFG"
    13 min read
    Find the GCD that lies in given range
    Given two positive integer a and b and a range [low, high]. The task is to find the greatest common divisor of a and b which lie in the given range. If no divisor exist in the range, print -1.Examples: Input : a = 9, b = 27, low = 1, high = 5 Output : 3 3 is the highest number that lies in range [1,
    7 min read
    Find the maximum GCD of the siblings of a Binary Tree
    Given a 2d-array arr[][] which represents the nodes of a Binary tree, the task is to find the maximum GCD of the siblings of this tree without actually constructing it. Example:   Input: arr[][] = {{4, 5}, {4, 2}, {2, 3}, {2, 1}, {3, 6}, {3, 12}} Output: 6 Explanation:   For the above tree, the maxi
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
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