Read pairs of numbers and print their GCD (with a while loop implementing Euclid's algorithm) and LCM (computed without overflow).
Solution
Main.java
import java.util.Scanner;
public class Main {
static long gcd(long a, long b) {
while (b != 0) {
long r = a % b;
a = b;
b = r;
}
return Math.abs(a);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLong()) {
long a = in.nextLong(), b = in.nextLong();
long g = gcd(a, b);
long lcm = g == 0 ? 0 : a / g * b; // divide first to avoid overflow
System.out.println("gcd(" + a + ", " + b + ") = " + g + ", lcm = " + lcm);
}
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!