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.
/** ** Java Program to Implement Stein GCD Algorithm **/ import java.util.Scanner; /** Class SteinGcd **/ public class SteinGcd { /** Function to calculate gcd **/ public int gcd(int u, int v) { int shift; if (u == 0) return v; if (v == 0) return u; for (shift = 0; ((u | v) & 1) == 0; ++shift) { u >>= 1; v >>= 1; } while ((u & 1) == 0) u >>= 1; do { while ((v & 1) == 0) v >>= 1; if (u > v) { int t = v; v = u; u = t; } v = v - u; } while (v != 0); return u << shift; } /** Main function **/ public static void main (String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Stein GCD Algorithm Test\n"); /** Make an object of SteingGcd class **/ SteinGcd sg = new SteinGcd(); /** Accept two integers **/ System.out.println("Enter two integer numbers\n"); int n1 = scan.nextInt(); int n2 = scan.nextInt(); /** Call function gcd of class SteinGcd **/ int gcd = sg.gcd(n1, n2); System.out.println("GCD of "+ n1 +" and "+ n2 +" = "+ gcd); } }
Output:
Stein GCD Algorithm Test Enter two integer numbers 32984 10013 GCD of 32984 and 10013 = 589
Related posts:
Java Program to Implement Iterative Deepening
OAuth 2.0 Resource Server With Spring Security 5
A Guide to JUnit 5
Life Cycle of a Thread in Java
Finding the Differences Between Two Lists in Java
Java Multi-line String
Send email with SMTPS (eg. Google GMail)
Java equals() and hashCode() Contracts
Spring Cloud Bus
Wiring in Spring: @Autowired, @Resource and @Inject
Java Program to Implement ConcurrentHashMap API
Java Program to Find Second Smallest of n Elements with Given Complexity Constraint
Java Program to Implement Strassen Algorithm
Java Program to Permute All Letters of an Input String
Java Program to Implement Bresenham Line Algorithm
Generic Constructors in Java
Java Program to Solve a Matching Problem for a Given Specific Case
Java Program to Generate Random Numbers Using Multiply with Carry Method
Comparing Strings in Java
Using JWT with Spring Security OAuth
Java – Try with Resources
Instance Profile Credentials using Spring Cloud
Check If a String Is Numeric in Java
Deque và ArrayDeque trong Java
Java Optional as Return Type
Phương thức forEach() trong java 8
Intro to the Jackson ObjectMapper
Java Program to Implement Ternary Heap
Java Program to Generate All Possible Combinations of a Given List of Numbers
Java Program to Implement Splay Tree
Guide to System.gc()
Hướng dẫn Java Design Pattern – Command