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:
Lập trình đa luồng với Callable và Future trong Java
ClassNotFoundException vs NoClassDefFoundError
Java Program to Implement TreeSet API
Convert Hex to ASCII in Java
Java Program to Check whether Graph is a Bipartite using 2 Color Algorithm
Logging in Spring Boot
Câu lệnh điều khiển vòng lặp trong Java (break, continue)
The Spring @Controller and @RestController Annotations
Java Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
How to Manually Authenticate User with Spring Security
Java Program to Generate a Random Subset by Coin Flipping
Java Program to Solve any Linear Equation in One Variable
Java Byte Array to InputStream
Spring Boot - Unit Test Cases
wait() and notify() Methods in Java
Split a String in Java
Overflow and Underflow in Java
Java Program to Implement Hamiltonian Cycle Algorithm
DistinctBy in the Java Stream API
Guide to the Java Clock Class
List Interface trong Java
Spring Boot - CORS Support
Hướng dẫn Java Design Pattern – Abstract Factory
Java Program to Generate All Possible Combinations of a Given List of Numbers
Uploading MultipartFile with Spring RestTemplate
New Stream Collectors in Java 9
Java Program to Test Using DFS Whether a Directed Graph is Strongly Connected or Not
Ways to Iterate Over a List in Java
Introduction to Eclipse Collections
LinkedHashSet trong Java hoạt động như thế nào?
Exploring the New Spring Cloud Gateway
Giới thiệu SOAP UI và thực hiện test Web Service