From aa7b95e6a156c03e5a3c0f04f6314566d8553660 Mon Sep 17 00:00:00 2001 From: vatsalgosar Date: Mon, 5 Aug 2019 23:28:19 +0530 Subject: [PATCH] BAEL-3115 - GCD implementation methods using Brute force, Euclid's Algo and Stein's Algo --- .../algorithms/gcd/GCDImplementation.java | 51 +++++++++++++++++++ .../gcd/GCDImplementationUnitTest.java | 32 ++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 java-math/src/main/java/com/baeldung/algorithms/gcd/GCDImplementation.java create mode 100644 java-math/src/test/java/com/baeldung/algorithms/gcd/GCDImplementationUnitTest.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/gcd/GCDImplementation.java b/java-math/src/main/java/com/baeldung/algorithms/gcd/GCDImplementation.java new file mode 100644 index 0000000000..df12c97162 --- /dev/null +++ b/java-math/src/main/java/com/baeldung/algorithms/gcd/GCDImplementation.java @@ -0,0 +1,51 @@ +package com.baeldung.algorithms.gcd; + +public class GCDImplementation { + + public static int gcdByBruteForce(int n1, int n2) { + int gcd = 1; + for (int i = 1; i <= n1 && i <= n2; i++) + if (n1 % i == 0 && n2 % i == 0) + gcd = i; + + return gcd; + } + + public static int gcdByEuclidsAlgorithm(int n1, int n2) { + if (n2 == 0) + return n1; + return gcdByEuclidsAlgorithm(n2, n1 % n2); + } + + public static int gcdBySteinsAlgorithm(int n1, int n2) { + + if (n1 == 0) + return n2; + + if (n2 == 0) + return n1; + + int n; + for (n = 0; ((n1 | n2) & 1) == 0; n++) { + n1 >>= 1; + n2 >>= 1; + } + + while ((n1 & 1) == 0) + n1 >>= 1; + + do { + while ((n2 & 1) == 0) + n2 >>= 1; + + if (n1 > n2) { + int temp = n1; + n1 = n2; + n2 = temp; + } + n2 = (n2 - n1); + } while (n2 != 0); + + return n1 << n; + } +} diff --git a/java-math/src/test/java/com/baeldung/algorithms/gcd/GCDImplementationUnitTest.java b/java-math/src/test/java/com/baeldung/algorithms/gcd/GCDImplementationUnitTest.java new file mode 100644 index 0000000000..d2c91a2eb8 --- /dev/null +++ b/java-math/src/test/java/com/baeldung/algorithms/gcd/GCDImplementationUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.algorithms.gcd; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GCDImplementationUnitTest { + + @Test + public void whenCalculatingGCDByBruteForceMethod_thenCorrect() { + int n1 = 60; + int n2 = 90; + int gcd = GCDImplementation.gcdByBruteForce(n1, n2); + assertThat(gcd).isEqualTo(30); + } + + @Test + public void whenCalculatingGCDByEuclidsAlgorithm_thenCorrect() { + int n1 = 60; + int n2 = 90; + int gcd = GCDImplementation.gcdByEuclidsAlgorithm(n1, n2); + assertThat(gcd).isEqualTo(30); + } + + @Test + public void whenCalculatingGCDBySteinsAlgorithm_thenCorrect() { + int n1 = 60; + int n2 = 90; + int gcd = GCDImplementation.gcdBySteinsAlgorithm(n1, n2); + assertThat(gcd).isEqualTo(30); + } +}