This is a Java Program to Implement Extended Euclid Algorithm. The extended Euclidean algorithm is an extension to the Euclidean algorithm. Besides finding the greatest common divisor of integers a and b, as the Euclidean algorithm does, it also finds integers x and y (one of which is typically negative) that satisfy Bézout’s identity
ax + by = gcd(a, b).
Here is the source code of the Java Program to Implement Extended Euclid Algorithm. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
/**
** Java Program to implement Extended Euclid Algorithm
**/
import java.util.Scanner;
/** Class ExtendedEuclid **/
public class ExtendedEuclid
{
/** Function to solve **/
public void solve(long a, long b)
{
long x = 0, y = 1, lastx = 1, lasty = 0, temp;
while (b != 0)
{
long q = a / b;
long r = a % b;
a = b;
b = r;
temp = x;
x = lastx - q * x;
lastx = temp;
temp = y;
y = lasty - q * y;
lasty = temp;
}
System.out.println("Roots x : "+ lastx +" y :"+ lasty);
}
/** Main function **/
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Extended Euclid Algorithm Test\n");
/** Make an object of ExtendedEuclid class **/
ExtendedEuclid ee = new ExtendedEuclid();
/** Accept two integers **/
System.out.println("Enter a b of ax + by = gcd(a, b)\n");
long a = scan.nextLong();
long b = scan.nextLong();
/** Call function solve of class ExtendedEuclid **/
ee.solve(a, b);
}
}
Output:
Extended Euclid Algorithm Test Enter a b of ax + by = gcd(a, b) 120 23 Roots x : -9 y :47
Related posts:
Convert Hex to ASCII in Java
Java Program to Implement CountMinSketch
Guide to the Volatile Keyword in Java
Spring Boot Change Context Path
Collect a Java Stream to an Immutable Collection
Java NIO2 Path API
Spring Boot - Code Structure
Spring Cloud AWS – Messaging Support
OAuth2.0 and Dynamic Client Registration
Java Program to Permute All Letters of an Input String
DistinctBy in the Java Stream API
Java Program to Implement Vector API
How to Change the Default Port in Spring Boot
Java Program to subtract two large numbers using Linked Lists
Hướng dẫn Java Design Pattern – Transfer Object
Introduction to Liquibase Rollback
Updating your Password
Java Program to find the maximum subarray sum O(n^2) time(naive method)
A Guide to TreeMap in Java
Batch Processing with Spring Cloud Data Flow
Introduction to the Java NIO Selector
Reactive Flow with MongoDB, Kotlin, and Spring WebFlux
Mix plain text and HTML content in a mail
Java Program to Use Boruvka’s Algorithm to Find the Minimum Spanning Tree
Java Program to Implement Quick sort
Finding the Differences Between Two Lists in Java
Java – Write to File
The “final” Keyword in Java
Java Program to Find a Good Feedback Edge Set in a Graph
Spring Security and OpenID Connect
Java Streams vs Vavr Streams
Date Time trong Java 8