0% found this document useful (0 votes)
10 views

L15 Euclid's Algorithm

Uploaded by

Siddharth Jha
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

L15 Euclid's Algorithm

Uploaded by

Siddharth Jha
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 14

EUCLID’S ALGORITHM

Introduction
Euclidean algorithm or Euclid's algorithm, is an efficient method for computing
the greatest common divisor (GCD) of two integers (numbers), the largest
number that divides them both without a remainder.

First the two numbers are subjected to prime factorizations, and the common
factors of the two prime factorizations are multiplied to get the GCD
Idea
The algorithm is based on the below facts:

If we subtract a smaller number from a larger (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 smaller number, the


algorithm stops when we find remainder 0.
import java.util.*;
class Main
{
public static int gcd(int a, int b)
{
if (a == 0)
return b;

return gcd(b%a, a);


}
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
System.out.println("Enter two integers -");
int n1 = scan.nextInt();
int n2 = scan.nextInt();
g = gcd(n1, n2);
System.out.println("GCD is "+g)
}
}
Extended Euclidean algorithm
also finds integer coefficients x and y such that:

ax + by = gcd(a, b)

The extended Euclidean algorithm updates results of gcd(a, b) using the results
calculated by 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.

x = y1 - ⌊b/a⌋ * x1
y = x1
The extended Euclidean algorithm is particularly useful when a and b are coprime.

With that provision, x is the modular multiplicative inverse of a modulo b, and y is


the modular multiplicative inverse of b modulo a.

Similarly, the polynomial extended Euclidean algorithm allows one to compute the
multiplicative inverse in algebraic field extensions and, in particular in finite fields
of non prime order.

It follows that both extended Euclidean algorithms are widely used in cryptography.

In particular, the computation of the modular multiplicative inverse is an essential


step in the derivation of key-pairs in the RSA public-key encryption method.
class EthCode
{
public static int gcdExtended(int a, int b, int x, int y)
{
if (a == 0)
{
x = 0;
y = 1;
return b;
}
int x1=1, y1=1;
int gcd = gcdExtended(b%a, a, x1, y1);
x = y1 - (b/a) * x1;
y = x1;

return gcd;
}
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 is " + g);
}
}
THANK YOU

You might also like