forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExtended_Euclidean_Algorithm.java
More file actions
46 lines (37 loc) · 925 Bytes
/
Extended_Euclidean_Algorithm.java
File metadata and controls
46 lines (37 loc) · 925 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.*;
public class Extended_Euclidean_Algorithm
{
// extended Euclidean Algorithm
public static int getGCD(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 = getGCD(b % a, a, x1, y1);
// Update x and y after recursive call
x = y1 - (b / a) * x1;
y = x1;
return gcd;
}
// Main function
public static void main(String[] args)
{
int x = 1, y = 1;
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int b = s.nextInt();
int g = getGCD(a, b, x, y);
System.out.print("GCD of " + a + " , " + b + " = " + g);
}
}
/*
INPUT
a = 35, b = 15;
Output:
GCD of 35 , 15 = 5
*/