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 Spring Data MongoDB
Java Program to Implement Gabow Algorithm
Java Program to Implement Binary Heap
Java Program to Perform Polygon Containment Test
Guide to Character Encoding
Guide to Java 8’s Collectors
Java Program to Perform Sorting Using B-Tree
Spring Boot Configuration with Jasypt
Spring 5 and Servlet 4 – The PushBuilder
Guide to Guava Multimap
Lớp Collectors trong Java 8
Tiêu chuẩn coding trong Java (Coding Standards)
Java Program to Encode a Message Using Playfair Cipher
Spring Web Annotations
Understanding Memory Leaks in Java
Java Program to Perform Cryptography Using Transposition Technique
Creating a Generic Array in Java
Spring Boot - Tomcat Port Number
Rest Web service: Filter và Interceptor với Jersey 2.x (P2)
Java Program to Check if it is a Sparse Matrix
Java Program to Check if a Given Set of Three Points Lie on a Single Line or Not
Introduction to Java 8 Streams
Java TreeMap vs HashMap
@Lookup Annotation in Spring
Java Program to Check whether Graph is Biconnected
Lập trình đa luồng với CompletableFuture trong Java 8
ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize
Hướng dẫn Java Design Pattern – Decorator
Giới thiệu Design Patterns
Java Program to Construct an Expression Tree for an Postfix Expression
Guide to Dynamic Tests in Junit 5
Java Program to Construct a Random Graph by the Method of Random Edge Selection