This is a Java Program to implement Euclid’s GCD Algorithm. This is a program to find GCD (Greatest Common Divisor) of two numbers using Euclid’s Algorithm.
Algorithm is as follows :
function gcd(a, b)
if b = 0
return a
else
return gcd(b, a mod b)
Here is the source code of the Java program to implement Euclids 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 Euclid GCD Algorithm
**/
import java.util.Scanner;
/** Class EuclidGcd **/
public class EuclidGcd
{
/** Function to calculate gcd **/
public long gcd(long p, long q)
{
if (p % q == 0)
return q;
return gcd(q, p % q);
}
/** Main function **/
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Euclid GCD Algorithm Test\n");
/** Make an object of EuclidGcd class **/
EuclidGcd eg = new EuclidGcd();
/** Accept two integers **/
System.out.println("Enter two integer numbers\n");
long n1 = scan.nextLong();
long n2 = scan.nextLong();
/** Call function gcd of class EuclidGcd **/
long gcd = eg.gcd(n1, n2);
System.out.println("\nGCD of "+ n1 +" and "+ n2 +" = "+ gcd);
}
}
Output:
Euclid GCD Algorithm Test Enter two integer numbers 257184 800128 GCD of 257184 and 800128 = 28576
Related posts:
Introduction to Java 8 Streams
Date Time trong Java 8
So sánh HashSet, LinkedHashSet và TreeSet trong Java
Java Program to Implement Find all Cross Edges in a Graph
Rest Web service: Filter và Interceptor với Jersey 2.x (P2)
Spring Security OAuth Login with WebFlux
OAuth2 for a Spring REST API – Handle the Refresh Token in Angular
Java Program to Implement Shunting Yard Algorithm
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Spring Boot - Internationalization
Sao chép các phần tử của một mảng sang mảng khác như thế nào?
Tránh lỗi NullPointerException trong Java như thế nào?
Remove the First Element from a List
Java Program to Implement the Edmond’s Algorithm for Maximum Cardinality Matching
Adding a Newline Character to a String in Java
How to Implement Caching using Adonis.js 5
Comparing Dates in Java
Java Program to implement Bi Directional Map
Weak References in Java
Spring Boot - Enabling Swagger2
Guide to Selenium with JUnit / TestNG
The Difference Between Collection.stream().forEach() and Collection.forEach()
Java Program to Implement ConcurrentSkipListMap API
Spring Cloud – Bootstrapping
Java Program to Implement CopyOnWriteArrayList API
Java Program to Solve Travelling Salesman Problem for Unweighted Graph
Java Program to Implement Extended Euclid Algorithm
Java Program to Generate Randomized Sequence of Given Range of Numbers
Hướng dẫn sử dụng biểu thức chính quy (Regular Expression) trong Java
Java Program to Implement Interval Tree
Java – Convert File to InputStream
Getting a File’s Mime Type in Java