The Wayback Machine - https://web.archive.org/web/20241005225340/https://www.geeksforgeeks.org/euclidean-algorithms-basic-and-extended/
Open In App

Euclidean algorithms (Basic and Extended)

Last Updated : 22 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Basic
54.93%
1.7K

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.
 

GCD

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.

Below is a recursive function to evaluate gcd using Euclid’s algorithm:

CPP

// C++ program to demonstrate // Basic Euclidean Algorithm #include <bits/stdc++.h> using namespace std; // Function to return // gcd of a and b int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Driver Code int main() { int a = 10, b = 15; // Function call cout << "GCD(" << a << ", " << b << ") = " << gcd(a, b) << endl; a = 35, b = 10; cout << "GCD(" << a << ", " << b << ") = " << gcd(a, b) << endl; a = 31, b = 2; cout << "GCD(" << a << ", " << b << ") = " << gcd(a, b) << endl; return 0; }

C

// C program to demonstrate Basic Euclidean Algorithm #include <stdio.h> // Function to return gcd of a and b int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Driver code int main() { int a = 10, b = 15; // Function call printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b)); a = 35, b = 10; printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b)); a = 31, b = 2; printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b)); return 0; }

Java

// Java program to demonstrate Basic Euclidean Algorithm import java.lang.*; import java.util.*; class GFG { // extended Euclidean Algorithm public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Driver code public static void main(String[] args) { int a = 10, b = 15, g; // Function call g = gcd(a, b); System.out.println("GCD(" + a + " , " + b + ") = " + g); a = 35; b = 10; g = gcd(a, b); System.out.println("GCD(" + a + " , " + b + ") = " + g); a = 31; b = 2; g = gcd(a, b); System.out.println("GCD(" + a + " , " + b + ") = " + g); } } // Code Contributed by Mohit Gupta_OMG <(0_o)>

Python

# Python3 program to demonstrate Basic Euclidean Algorithm # Function to return gcd of a and b def gcd(a, b): if a == 0: return b return gcd(b % a, a) # Driver code if __name__ == "__main__": a = 10 b = 15 print("gcd(", a, ",", b, ") = ", gcd(a, b)) a = 35 b = 10 print("gcd(", a, ",", b, ") = ", gcd(a, b)) a = 31 b = 2 print("gcd(", a, ",", b, ") = ", gcd(a, b)) # Code Contributed By Mohit Gupta_OMG <(0_o)>

C#

// C# program to demonstrate Basic Euclidean Algorithm using System; class GFG { public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Driver Code static public void Main() { int a = 10, b = 15, g; g = gcd(a, b); Console.WriteLine("GCD(" + a + " , " + b + ") = " + g); a = 35; b = 10; g = gcd(a, b); Console.WriteLine("GCD(" + a + " , " + b + ") = " + g); a = 31; b = 2; g = gcd(a, b); Console.WriteLine("GCD(" + a + " , " + b + ") = " + g); } } // This code is contributed by ajit

JavaScript

// JavaScript program to demonstrate // Basic Euclidean Algorithm // Function to return // gcd of a and b function gcd( a, b) { if (a == 0) return b; return gcd(b % a, a); } // Driver Code let a = 10, b = 15; document.write( "GCD(" + a + ", " + b + ") = " + gcd(a, b) +"<br/>"); a = 35, b = 10; document.write( "GCD(" + a + ", " + b + ") = " + gcd(a, b) +"<br/>"); a = 31, b = 2; document.write( "GCD(" + a + ", " + b + ") = " + gcd(a, b) +"<br/>"); // This code contributed by aashish1995

PHP

// php program to demonstrate Basic Euclidean Algorithm <?php // PHP program to demonstrate // Basic Euclidean Algorithm // Function to return // gcd of a and b function gcd($a, $b) { if ($a == 0) return $b; return gcd($b % $a, $a); } // Driver Code $a = 10; $b = 15; // Function call echo "GCD(",$a,"," , $b,") = ", gcd($a, $b); echo "\n"; $a = 35; $b = 10; echo "GCD(",$a ,",",$b,") = ", gcd($a, $b); echo "\n"; $a = 31; $b = 2; echo "GCD(",$a ,",", $b,") = ", gcd($a, $b); // This code is contributed by m_kit ?>


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
(Note that 30*1 + 20*(-1) = 10)

Input: a = 35, b = 15
Output: gcd = 5, x = 1, y = -2
(Note that 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 – [Tex]\lfloor b/a \rfloor[/Tex]* x1
 y = x1

Below is an implementation of the above approach:

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; // To store results of recursive call 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; } // Driver Code int main() { int x, y, a = 35, b = 15; int g = gcdExtended(a, b, &x, &y); cout << "GCD(" << a << ", " << b << ") = " << g << endl; return 0; }

C

// C program to demonstrate working of extended // Euclidean Algorithm #include <stdio.h> // C 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; // To store results of recursive call 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; } // Driver Program int main() { int x, y; int a = 35, b = 15; int g = gcdExtended(a, b, &x, &y); printf("gcd(%d, %d) = %d", a, b, g); return 0; }

Java

// Java program to demonstrate working of extended // Euclidean Algorithm import java.lang.*; import java.util.*; class GFG { // extended Euclidean Algorithm public static int gcdExtended(int a, int b, int x, int y) { // Base Case if (a == 0) { x = 0; y = 1; return b; } int x1 = 1, y1 = 1; // To store results of recursive call 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; } // Driver Program public static void main(String[] args) { int x = 1, y = 1; int a = 35, b = 15; int g = gcdExtended(a, b, x, y); System.out.print("gcd(" + a + " , " + b + ") = " + g); } }

Python

# Python program to demonstrate working of extended # Euclidean Algorithm # function for extended Euclidean Algorithm def gcdExtended(a, b): # Base Case if a == 0: return b, 0, 1 gcd, x1, y1 = gcdExtended(b % a, a) # Update x and y using results of recursive # call x = y1 - (b//a) * x1 y = x1 return gcd, x, y # Driver code a, b = 35, 15 g, x, y = gcdExtended(a, b) print("gcd(", a, ",", b, ") = ", g)

C#

// C# program to demonstrate working // of extended Euclidean Algorithm using System; class GFG { // extended Euclidean Algorithm public static int gcdExtended(int a, int b, int x, int y) { // Base Case if (a == 0) { x = 0; y = 1; return b; } // To store results of // recursive call int x1 = 1, y1 = 1; 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; } // Driver Code static public void Main () { int x = 1, y = 1; int a = 35, b = 15; int g = gcdExtended(a, b, x, y); Console.WriteLine("gcd(" + a + " , " + b + ") = " + g); } }

JavaScript

<script> // Javascript program to demonstrate // working of extended // Euclidean Algorithm // Javascript function for // extended Euclidean // Algorithm function gcdExtended(a, b, x, y) { // Base Case if (a == 0) { x = 0; y = 1; return b; } // To store results // of recursive call let gcd = gcdExtended(b % a, a, x, y); // Update x and y using // results of recursive // call x = y - (b / a) * x; y = x; return gcd; } // Driver Code let x = 0; let y = 0; let a = 35; let b = 15; let g = gcdExtended(a, b, x, y); document.write("gcd(" + a); document.write(", " + b + ")"); document.write(" = " + g); </script>

PHP

<?php // PHP program to demonstrate // working of extended // Euclidean Algorithm // PHP function for // extended Euclidean // Algorithm function gcdExtended($a, $b, $x, $y) { // Base Case if ($a == 0) { $x = 0; $y = 1; return $b; } // To store results // of recursive call $gcd = gcdExtended($b % $a, $a, $x, $y); // Update x and y using // results of recursive // call $x = $y - floor($b / $a) * $x; $y = $x; return $gcd; } // Driver Code $x = 0; $y = 0; $a = 35; $b = 15; $g = gcdExtended($a, $b, $x, $y); echo "gcd(",$a; echo ", " , $b, ")"; echo " = " , $g; ?>

Output : 

gcd(35, 15) = 5

Time Complexity: O(log N)
Auxiliary Space: O(log N)

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 = [Tex](b – (\lfloor b/a \rfloor).a)[/Tex] in above, 
we get following. Note that [Tex]\lfloor b/a\rfloor[/Tex] is floor(b/a)

[Tex](b – (\lfloor b/a \rfloor).a).x1 + a.y1  = gcd[/Tex]

Above equation can also be written as below

[Tex]b.x1 + a.(y1 – (\lfloor b/a \rfloor).x1) = gcd [/Tex]     —(2)

After comparing coefficients of ‘a’ and ‘b’ in (1) and 
(2), we get following, 
[Tex]x = y1 – \lfloor b/a \rfloor * x1[/Tex]
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.



Previous Article
Next Article

Similar Reads

Pairs with same Manhattan and Euclidean distance
In a given Cartesian plane, there are N points. The task is to find the Number of Pairs of points(A, B) such that Point A and Point B do not coincide.Manhattan Distance and the Euclidean Distance between the points should be equal.Note: Pair of 2 points(A, B) is considered same as Pair of 2 points(B, A). Manhattan Distance = |x2-x1|+|y2-y1|Euclidea
10 min read
Find HCF of two numbers without using recursion or Euclidean algorithm
Given two integer x and y, the task is to find the HCF of the numbers without using recursion or Euclidean method. Examples: Input: x = 16, y = 32 Output: 16 Input: x = 12, y = 15 Output: 3 Approach: HCF of two numbers is the greatest number which can divide both the numbers. If the smaller of the two numbers can divide the larger number then the H
6 min read
Calculate the Square of Euclidean Distance Traveled based on given conditions
Given an array commands[], consisting of signed integers denoting distance and direction to be travelled along with the coordinates, and array obstacles[] denoting the coordinates which cannot be accessed, the task is to find the square of the square of maximum Euclidean distance that can be travelled started from the origin (0, 0) and facing north
7 min read
Time Complexity of Euclidean Algorithm
In this article, we will discuss the time complexity of the Euclidean Algorithm which is O(log(min(a, b)) and it is achieved. Euclid's Algorithm: It is an efficient method for finding the GCD(Greatest Common Divisor) of two integers. The time complexity of this algorithm is O(log(min(a, b)). Recursively it can be expressed as: gcd(a, b) = gcd(b, a%
4 min read
Number of Triangles that can be formed given a set of lines in Euclidean Plane
Given a set L = {l1, l2, ……..., ln} of ‘n’ distinct lines on the Euclidean Plane. The ith line is given by an equation in the form aix + biy = ci. Find the number of triangles that can be formed using the lines in the set L. Note that no two pairs of lines intersect at the same point. Note: This problem doesn’t mention that the lines can’t be paral
13 min read
Find the winner by incrementing co-ordinates till Euclidean distance <= D
A and B play a game and A starts first. Consider a Token placed at (0,0) in a 2D plane, a player can perform the below moves on the token: increase x coordinate of the token to x+K increase y coordinate of the token to y+K After each move the euclidean distance of the token from origin should be smaller than equal to D. i.e. x2 + y2 <= D2 . The
6 min read
Minimum Sum of Euclidean Distances to all given Points
Given a matrix mat[][] consisting of N pairs of the form {x, y} each denoting coordinates of N points, the task is to find the minimum sum of the Euclidean distances to all points. Examples: Input: mat[][] = { { 0, 1}, { 1, 0 }, { 1, 2 }, { 2, 1 }} Output: 4 Explanation: Average of the set of points, i.e. Centroid = ((0+1+1+2)/4, (1+0+2+1)/4) = (1,
6 min read
CSES Solutions - Minimum Euclidean Distance
Given a set of points in the two-dimensional plane, your task is to find the minimum Euclidean distance between two distinct points. The Euclidean distance of points (x1,y1) and (x2,y2) is sqrt( (x1-x2)2 + (y1-y2)2 ) Example: Input: points = {{2, 1} ,{4, 4} ,{1, 2} ,{6, 3}};Output: 2 Input: points = {{2, 12} ,{1, 4} ,{3, 2} ,{1, 3}}Output: 1 Approa
7 min read
Find sum of Kth largest Euclidean distance after removing ith coordinate one at a time
Given N integer coordinates where X[i] denotes the x-coordinate and Y[i] denotes the y-coordinate of the ith coordinate, the task is to find the sum of Kth largest euclidean distance between all the coordinate pairs except the ith coordinate for all possible values of i in the range [1, N]. Examples: Input: X[] = {0, 0, 1, 1}, Y[] = {0, 1, 0, 1}, K
12 min read
Extended Midy's theorem
According to Midy's theorem, if the period of a repeating decimal for [Tex]a / p [/Tex], where p is prime and [Tex]a / p [/Tex]is a reduced fraction, has an even number of digits, then dividing the repeating portion into halves and adding gives a string of 9s. For example 1/7 = 0.14285714285.. is a repeating decimal with 142857 being repeated. Now,
13 min read
Extended Binary Tree
Extended binary tree is a type of binary tree in which all the null sub tree of the original tree are replaced with special nodes called external nodes whereas other nodes are called internal nodes Here the circles represent the internal nodes and the boxes represent the external nodes.Properties of External binary tree The nodes from the original
5 min read
Extended Disjoint Set Union on Trees
Prerequisites: DFS, Trees, DSUGiven a tree with of N nodes from value 1 to N and E edges and array arr[] which denotes number associated to each node. You are also given Q queries which contains 2 integers {V, F}. For each query, there is a subtree with vertex V, the task is to check if there exists count of numbers associated with each node in tha
15 min read
Extended Mo's Algorithm with ≈ O(1) time complexity
Given an array of n elements and q range queries (range sum in this article) with no updates, task is to answer these queries with efficient time and space complexity. The time complexity of a range query after applying square root decomposition comes out to be O(?n). This square-root factor can be decreased to a constant linear factor by applying
15+ min read
Extended Knapsack Problem
Given N items, each item having a given weight Ci and a profit value Pi, the task is to maximize the profit by selecting a maximum of K items adding up to a maximum weight W. Examples: Input: N = 5, P[] = {2, 7, 1, 5, 3}, C[] = {2, 5, 2, 3, 4}, W = 8, K = 2. Output: 12 Explanation: Here, the maximum possible profit is when we take 2 items: item2 (P
12 min read
Bitwise Algorithms - Basic Practice Problems
Bitwise algorithms are a category of algorithms that operate on individual bits within a data unit, rather than the entire data unit itself. They leverage bitwise operators, which are special operators designed to perform operations on bits. Common bitwise operators include AND (&), OR (|), XOR (^), and NOT (~). Before diving into the world of
5 min read
Basic Properties of a Graph
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. The basic properties of a graph include: Vertices (nodes): The points where edges meet in a graph are known as vertices or nodes. A vertex can represent a
4 min read
Some Basic Theorems on Trees
Tree:- A connected graph without any circuit is called a Tree. In other words, a tree is an undirected graph G that satisfies any of the following equivalent conditions: Any two vertices in G can be connected by a unique simple path. G is acyclic, and a simple cycle is formed if any edge is added to G. G is connected and has no cycles. G is connect
6 min read
Menu driven program in C++ to perform various basic operations on array
Prerequisite: Switch Statement in C/C++, Functions in C/C++, Loops in C and C++, C/C++ do-while loop with Examples Write a menu-driven program to perform below various basic operations in the array: Print all the even values in the array.Print all the odd values in the array.Sum & average of elements in the array.Find the maximum and minimum el
5 min read
Minimum number of basic logic gates required to realize given Boolean expression
Given a string S of length N representing a boolean expression, the task is to find the minimum number of AND, OR, and NOT gates required to realize the given expression. Examples: Input: S = "A+B.C"Output: 2Explanation: Realizing the expression requires 1 AND gate represented by '.' and 1 OR gate represented by '+'. Input: S = "(1 - A). B+C"Output
4 min read
Basic Operations for Queue in Data Structure
Basic Operations on Queue: Some of the basic operations for Queue in Data Structure are: enqueue() - Insertion of elements to the queue.dequeue() - Removal of elements from the queue.peek() or front()- Acquires the data element available at the front node of the queue without deleting it.rear() - This operation returns the element at the rear end w
11 min read
Basic Coding Problems in DSA for Beginners
For any beginner looking to strengthen their skills in Data structures and algorithms (DSA), we have brought to you a collection of basic coding problems. These carefully selected problems will provide a solid foundation in fundamental concepts, helping beginners enhance their logical thinking and problem-solving abilities. Below is the list of Bas
2 min read
Basic Algorithm Techniques Not Taught in Academics
We generally study most of the algorithmic techniques in academics like Searching, Sorting, Dynamic Programming, Greedy Algorithms, Divide and Conquer, Backtracking, etc. But below techniques are generally not taught and used a lot to solve questions in interviews and competitive programming. Prefix Sum Technique In this technique we preprocess the
3 min read
Basic Operators in Java
Java provides a rich operator environment. We can classify the basic operators in java in the following groups: Arithmetic OperatorsRelational OperatorsBitwise OperatorsAssignment OperatorsLogical Operators Let us now learn about each of these operators in detail. 1. Arithmetic Operators: Arithmetic operators are used to perform arithmetic/mathemat
10 min read
Check if a given string is a valid number (Integer or Floating Point) | SET 1(Basic approach)
Validate if a given string is numeric. Examples: Input : str = "11.5" Output : true Input : str = "abc" Output : false Input : str = "2e10" Output : true Input : 10e5.4 Output : false The following cases need to be handled in the code. Ignore the leading and trailing white spaces.Ignore the '+', '-' and'.' at the start.Ensure that the characters in
11 min read
Career Path After Learning Basic Programming Languages & Data Structures
The career path after acquiring proficiency in basic programming languages and data structures is an important journey in the field of technology. After learning foundational skills, individuals gain entry into a world of opportunities, from excelling in coding competitions and securing internships to shaping efficient software applications and adv
4 min read
Peterson's Algorithm for Mutual Exclusion | Set 1 (Basic C implementation)
Problem: Given 2 processes i and j, you need to write a program that can guarantee mutual exclusion between the two without any additional hardware support. Solution: There can be multiple ways to solve this problem, but most of them require additional hardware support. The simplest and the most popular way to do this is by using Peterson's Algorit
11 min read
Basic String Operations with Implementation
In this post, we will look into some of the basic String operations such as: Accessing characters by index in a string. Inserting character into a String. Modifying character in String Deletion of Character in String Concatenating strings (combining multiple strings into one). Finding the length of a string Comparing strings for equality or lexicog
15+ min read
Basic Operations in Stack Data Structure with Implementations
In order to make manipulations in a stack, there are certain operations provided to us for Stack, which include: push() to insert an element into the stackpop() to remove an element from the stacktop() Returns the top element of the stack.isEmpty() returns true if the stack is empty else false.size() returns the size of the stack.In this post, we w
14 min read
Basic Geometry for Competitive Programming
Ever wondered how to tackle tricky problems in competitive programming? Well, basic geometry is your secret weapon! In this article, we're diving into the basics Geometric Algorithms. It's like a power-up for your problem-solving skills, giving you the tools to crack those coding challenges like a pro. Table of Content What are Geometric Algorithms
15+ min read
Basic Terminologies of Linked List
Linked List is a linear data structure, in which elements are not stored at a contiguous location, rather they are linked using pointers. Linked List forms a series of connected nodes, where each node stores the data and the address of the next node. Node Structure: A node in a linked list typically consists of two components: Data: It holds the ac
3 min read
Article Tags :
Practice Tags :