In: Computer Science
java
euclidean algorithm
(1) Let a = 35, and b = -49. Please compute GCD(a, b).
(2) Let a = 52, and b = 3. Please compute the quotient and remainder of a/b.
(3) Let a = -94, and b = 7. Please compute the quotient and remainder of a/b.
(4) Let a = 123, and b = 22. Please compute a mod b.
(5) Let a = -204, and b = 17. Please compute a mod b.
public class GCDEuclidean { public static int gcd(int n1, int n2) { n1 = (n1 > 0) ? n1 : -n1; n2 = (n2 > 0) ? n2 : -n2; while (n1 != n2) { if (n1 > n2) n1 -= n2; else n2 -= n1; } return n1; } public static void main(String[] args) { System.out.println("gcd(35, -49) is " + gcd(35, -49)); System.out.println("a = 52, b = 3, quotient = " + (52/3) + ", remainder = " + (52%3)); System.out.println("a = -94, b = 7, quotient = " + (-94/7) + ", remainder = " + (-94%7)); System.out.println("a = 123, b = 22, a mod b = " + (123 % 22)); System.out.println("a = -204, b = 17, a mod b = " + (-204 % 17)); } }