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:
Spring 5 and Servlet 4 – The PushBuilder
Tính đa hình (Polymorphism) trong Java
Introduction to Spring MVC HandlerInterceptor
Hướng dẫn Java Design Pattern – Command
Java Program to Compute Cross Product of Two Vectors
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
Một số nguyên tắc, định luật trong lập trình
Mix plain text and HTML content in a mail
Converting a Stack Trace to a String in Java
Java – Generate Random String
The DAO with JPA and Spring
Spring Boot - Servlet Filter
Spring Boot - OAuth2 with JWT
Summing Numbers with Java Streams
Spring Cloud AWS – EC2
The Difference Between Collection.stream().forEach() and Collection.forEach()
ArrayList trong java
Java Program to Implement Strassen Algorithm
New Stream Collectors in Java 9
Java Program to Check whether Graph is a Bipartite using 2 Color Algorithm
Versioning a REST API
Java Program to Implement Network Flow Problem
Logout in an OAuth Secured Application
Sử dụng Fork/Join Framework với ForkJoinPool trong Java
So sánh HashMap và HashSet trong Java
Introduction to Liquibase Rollback
Hướng dẫn sử dụng biểu thức chính quy (Regular Expression) trong Java
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set
Java Program to Implement Control Table
Examine the internal DNS cache
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
Guide to PriorityBlockingQueue in Java