Create a JAVA program to find the greatest common divisor and least common multiple.
The algorithm for finding the greatest common divisor and the least common multiple is explained.
The greatest common divisor is calculated by Euclidean algorithm. In Euclidean algorithm, the equation of division
In, the greatest common divisor of $ a $ and $ b $ is calculated using the property that it is equal to the greatest common divisor of $ r $ and $ b $. (Reference: Beautiful story of high school mathematics)
The procedure to obtain is as follows. (Reference: Example program for finding the greatest common divisor)
For two natural numbers a and b (a> = b)
Computational complexity is $ O (\ log (\ min (a, b)) $
The least common multiple $ lcm $ of the two natural numbers $ a $ and $ b $ is calculated by the following equation, where the greatest common divisor of $ a $ and $ b $ is $ gcd
The implemented program is as follows.
Euclid.java
public class Euclid{
public static int gcd(int a,int b){
if(a <= 0 || b <= 0){
return -1;
}
else if(a < b){
int tmp = a;
a = b;
b = tmp;
}
if(a % b == 0)
return b;
else
return gcd(b,a%b);
}
public static int lcm(int a,int b){
return a / gcd(a,b) * b;
}
}
EuclidMain.java
import java.util.Scanner;
public class EuclidMain{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Input 2 natural numbers.");
int a = scan.nextInt();
int b = scan.nextInt();
System.out.println("Greatest common divisor.");
System.out.println(Euclid.gcd(a,b));
System.out.println("Least common multiple.");
System.out.println(Euclid.lcm(a,b));
}
}
>javac EuclidMain.java
>java EuclidMain
Input 2 natural numbers.
12 9
Greatest common divisor.
3
Least common multiple.
36
-Euclidean algorithm and indefinite equation | Beautiful story of high school mathematics
Recommended Posts