# Java Program to Implement Stein GCD Algorithm

This is a Java Program to Implement Stein GCD Algorithm. The binary GCD algorithm, also known as Stein’s algorithm, is an algorithm that computes the greatest common divisor of two nonnegative integers. Stein’s algorithm uses simpler arithmetic operations than the conventional Euclidean algorithm. It replaces division with arithmetic shifts, comparisons and subtraction.

Here is the source code of the Java Program to Implement Stein GCD Algorithm. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

1. `/**`
2. ` ** Java Program to Implement Stein GCD Algorithm`
3. ` **/`
4. ` `
5. `import java.util.Scanner;`
6. ` `
7. `/** Class SteinGcd **/`
8. `public class SteinGcd`
9. `{`
10. `    /** Function to calculate gcd **/`
11. `    public int gcd(int u, int v)`
12. `    {`
13. `        int shift;`
14. `        if (u == 0)`
15. `            return v;`
16. `        if (v == 0)`
17. `            return u;`
18. `        for (shift = 0; ((u | v) & 1) == 0; ++shift) `
19. `        {`
20. `            u >>= 1;`
21. `            v >>= 1;`
22. `        }`
23. `        while ((u & 1) == 0)`
24. `            u >>= 1;`
25. `        do `
26. `        {`
27. `            while ((v & 1) == 0)  `
28. `                v >>= 1;`
29. ` `
30. `            if (u > v) `
31. `            {`
32. `                int t = v; `
33. `                v = u; `
34. `                u = t;`
35. `            }  `
36. `            v = v - u;                      `
37. `        } while (v != 0);`
38. ` `
39. `        return u << shift; `
40. `    }`
41. `    /** Main function **/`
42. `    public static void main (String[] args) `
43. `    {`
44. `        Scanner scan = new Scanner(System.in);`
45. `        System.out.println("Stein GCD Algorithm Test\n");`
46. `        /** Make an object of SteingGcd class **/`
47. `        SteinGcd sg = new SteinGcd();`
48. ` `
49. `        /** Accept two integers **/`
50. `        System.out.println("Enter two integer numbers\n");`
51. `        int n1 = scan.nextInt();`
52. `        int n2 = scan.nextInt();`
53. `        /** Call function gcd of class SteinGcd **/`
54. `        int gcd = sg.gcd(n1, n2);`
55. `        System.out.println("GCD of "+ n1 +" and "+ n2 +" = "+ gcd);`
56. `    }`
57. `}`

```Stein GCD Algorithm Test

Enter two integer numbers

32984 10013
GCD of 32984 and 10013 = 589```

Sanfoundry Global Education & Learning Series – 1000 Java Programs.