BAEL-3115

- GCD implementation methods using Brute force, Euclid's Algo and Stein's Algo
This commit is contained in:
vatsalgosar 2019-08-05 23:28:19 +05:30
parent 13c44baf7d
commit aa7b95e6a1
2 changed files with 83 additions and 0 deletions

View File

@ -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;
}
}

View File

@ -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);
}
}