DAA: Euclid Algorithm

Euclid Algorithm

The Euclid algorithm finds the GCD of two numbers in the efficient time complexity.

To find the GCD of two numbers, we take the two numbers’ common factors and multiply them.

For example :

Let us take two numbers36 and 60, whose GCD is 12.

           36 = 2 * 2 * 3 * 3
           60 = 2 * 2 * 3 * 5 

Basic Euclid algorithm :

The following define this algorithm

  • If we subtract a smaller number from a larger (we reduce a larger number), the GCD doesn’t change. So if we keep repeatedly subtracting the larger of two, we end up with GCD.
  • Instead of subtraction, if we divide the smaller number, the algorithm stops when we find remainder 0.

The approach implementation is shown below -

C++ code:

 #include <bits/stdc++.h>
 using namespace std;
 // This function will return the GCD of a and b
  int gcd(int a, int b)
 {
     if (a == 0)
         return b;
     return gcd(b % a, a);
 }
 int main()
 {
     int a = 10, b = 15;
     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 code -

 #include <stdio.h>
 int gcd(int a, int b)
 {
     if (a == 0)
         return b;
     return gcd(b % a, a);
 }
 int main()
 {
     int a = 10, b = 15;
     printf("GCD(%d, %d) = %dn", a, b, gcd(a, b));
     a = 35, b = 10;
     printf("GCD(%d, %d) = %dn", a, b, gcd(a, b));
     a = 31, b = 2;
     printf("GCD(%d, %d) = %dn", a, b, gcd(a, b));
     return 0;
 } 

Java code:

 import java.util.*;
 import java.lang.*;
 class Euclid {
  public static int gcd(int a, int b)
     {
         if (a == 0)
             return b;
         return gcd(b % a, a);
     }
 public static void main(String[] args)
     {
         int a = 10, b = 15, g;
         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);
     }
 } 

Output:

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

Time complexity: O(Log min(a, b)), where a and b are the numbers

Extended Euclid Algorithm:

The extended 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 algorithm modifies the results of our gcd using the recursive calls. Assume that x1 and y1 are the values created after recursive call of x and y.  The updated x and y will be:

 x = y1 - ?b/a? * x1
 y = x1 

C++ code:

 #include <bits/stdc++.h>
 using namespace std;
 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 main()
 {
     int x, y, a = 35, b = 15;
     int g = gcdExtended(a, b, &x, &y);
     cout << "GCD(" << a << ", " << b<< ") = " << g << endl;
     return 0;
 } 

C code:

 #include <stdio.h>
 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;
 }
 // Main Function
 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 code:

 import java.util.*;
 import java.lang.*;
 class Euclid
 {
           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;
           }
 // Main function 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);
           }
 } 

Output:

gcd(35, 15) = 5

How does extend Euclid works 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 - (?b/a?).a) in above,

we get following. Note that ?b/a? is floor(b/a)

   (b - (?b/a?).a).x1 + a.y1  = gcd

Above equation can also be written as below

   b.x1 + a.(y1 - (?b/a?).x1) = gcd      ---(2)

After comparing coefficients of 'a' and 'b' in (1) and

(2), we get following

   x = y1 - ?b/a? * x1

   y = x1


Related Topics

DAA: Density of a Binary Tree Algorithm

The Density of a Binary Tree Algorithm The density of a binary tree is defined as the ratio of the tree’s size to the tree’s height.  The height of the tree is...

2 minutes read.

Segregate the given Linked List in DAA

Segregate Even and Odd Nodes in a Linked List A linked list is a linear data structure in which each node has two blocks. One contains the node’s value or data,...

3 minutes read.

DAA: KMP Algorithm

KMP ALGORITHM The KMP algorithm is abbreviated as the "Knuth Morris Pratt” algorithm. This algorithm was developed by all of them.  This algorithm searches a pattern of length m in a string...

10 minutes read.

DAA: Euclid Algorithm

Euclid Algorithm The Euclid algorithm finds the GCD of two numbers in the efficient time complexity. To find the GCD of two numbers, we take the two numbers’ common factors and multiply...

8 minutes read.

DAA: Dijkstra’s Algorithm (Shortest Path)

Dijkstra’s Algorithm (Shortest Path) Dijkstra’s algorithm finds the shortest distance from a source to all the vertices in a graph. This algorithm is used in network protocols like IS-IS and OSPF(Open...

3 minutes read.

DAA: Find the Height or Maximum Depth of a Binary Tree

Find the Height or Maximum Depth of a Binary Tree We have a binary tree structure and we need to find its height. It is defined by the distance from the...

3 minutes read.

DAA: Breadth First Search (BFS) for a Graph

Breadth First Search (Bfs) For A Graph The algorithm in which all the graph nodes are traversed is known as the breadth-first search algorithm. In this algorithm, we select one node,...

5 minutes read.

DAA: Floyd Cycle Detection

Floyd Cycle Detection Floyd Cycle algorithm is one of the cycle detection algorithms to detect the cycle in a given singly linked list. In the Floyd Cycle algorithm, we have two pointers...

4 minutes read.

DAA: Algorithm to Find the Maximum Width of a Tree

Algorithm to Find the Maximum Width of a Tree The width of a binary tree is defined as the maximum number of nodes at a given level. The level having the...

5 minutes read.

DAA: Binary Tree and its Categories

Binary Tree and its Categories The binary tree is a non-linear data structure in which there are 0 or utmost 2 nodes.  Each node has two children, i.e., left and right...

4 minutes read.

DAA: Application of DFS and BFS

Application of DFS and BFS Depth-first search and breadth-first searches are the most famous algorithms used in daily life and the programming world. Let us now explore each application in which...

3 minutes read.

DAA: Rabin Karp Algorithm

Rabin Karp Algorithm The Rabin Karp or Karp Rabin algorithm is used to matching a specific pattern in the string. It uses the technique of hashing to match a specific text. There also...

6 minutes read.

DAA: Bead Sort Algorithm

Bead Sort Algorithm The bead sort is also known as the gravity sort algorithm. The algorithm is based on the natural phenomena of gravity. The phenomenon is the falling of things...

3 minutes read.

Introduction to Sorting in DAA

DAA: What is Sorting? The technique in which a data structure is rearranged in decreasing order, increasing order, or in a specified order is called sorting. We apply to sort in our...

4 minutes read.

DAA: Expression Trees

Expression Trees Expression trees are those in which the leaf nodes have the values to be operated, and internal nodes contain the operator on which the leaf node will be performed. Example:...

4 minutes read.

DAA: Construct a Tree from Inorder and Preorder Traversals

Construct a Tree from Inorder and Preorder Traversals We are given inorder and preorder traversals of a tree. We need to generate a tree from these traversals. Example: Inorder[]   = { 3, 1,...

4 minutes read.

DAA: Algorithm of Right View of a Binary Tree

Algorithm of Right View of a Binary Tree The right view of a binary tree is the visible nodes from the right side of the tree. In the given tree, the visible...

5 minutes read.

DAA: Insert a node in Binary Search Tree

Insert a node in Binary Search Tree (BST) We have a Binary search tree and a key. Insert the key in the binary search tree if not present. In the above figure,...

4 minutes read.

DAA: Interpolation Search Algorithm

Interpolation Search Algorithm There is no doubt that binary search is a great algorithm with average time complexity of log n. The feature of discarding one half of the array reduces...

4 minutes read.

DAA: Continuous Tree

Continuous Tree A continuous tree is the one in which the nodes from root to leaf path, the two adjacent node values, have a difference of 1. Input :          3                     /   \                   ...

5 minutes read.