From e56fcf9023ba43919cae20393a2b85d89206271c Mon Sep 17 00:00:00 2001 From: Haidong Ji Date: Sun, 19 Aug 2018 10:24:13 -0500 Subject: GCD done! Interesting. The original code was like this: public static int getGCD(int a, int b) { if (b == 0) { return a; } if (b > a) { return getGCD(b, b % a); } else { return getGCD(b, a % b); } } And it failed the test of 14159572, 63967072. After chaning the code to: public static int getGCD(int a, int b) { if (b == 0) { return a; } if (b > a) { return getGCD(b, a); } else { return getGCD(b, a % b); } } It worked! I guess it's important to do a pretty exhaustive testing to find this subtle bug--- AlgoDesignAndTechniqueEdxJava/sources/GCD.java | 24 +++++++++++++++++ AlgoDesignAndTechniqueEdxJava/tests/GCDTest.java | 33 ++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 AlgoDesignAndTechniqueEdxJava/sources/GCD.java create mode 100644 AlgoDesignAndTechniqueEdxJava/tests/GCDTest.java diff --git a/AlgoDesignAndTechniqueEdxJava/sources/GCD.java b/AlgoDesignAndTechniqueEdxJava/sources/GCD.java new file mode 100644 index 0000000..5e29e4f --- /dev/null +++ b/AlgoDesignAndTechniqueEdxJava/sources/GCD.java @@ -0,0 +1,24 @@ +import java.util.Scanner; + +public class GCD { + + public static int getGCD(int a, int b) { + if (b == 0) { + return a; + } + + if (b > a) { + return getGCD(b, a); + } else { + return getGCD(b, a % b); + } + } + + public static void main(String args[]) { + Scanner in = new Scanner(System.in); + int a = in.nextInt(); + int b = in.nextInt(); + + System.out.println(getGCD(a, b)); + } +} diff --git a/AlgoDesignAndTechniqueEdxJava/tests/GCDTest.java b/AlgoDesignAndTechniqueEdxJava/tests/GCDTest.java new file mode 100644 index 0000000..1c8fedd --- /dev/null +++ b/AlgoDesignAndTechniqueEdxJava/tests/GCDTest.java @@ -0,0 +1,33 @@ +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + +public class GCDTest { + @Test + void testGCD1() { + assertEquals(1, GCD.getGCD(18, 35)); + } + @Test + void testGCD2() { + assertEquals(17657, GCD.getGCD(28851538, 1183019)); + } + + @Test + void testGCD3() { + assertEquals(7, GCD.getGCD(1344, 217)); + } + + @Test + void testGCD4() { + assertEquals(1344, GCD.getGCD(1344, 1344)); + } + + @Test + void testGCD5() { + assertEquals(4, GCD.getGCD(14159572, 63967072)); + } + + @Test + void testGCD6() { + assertEquals(4, GCD.getGCD(63967072,14159572)); + } +} -- cgit v1.2.3