Merge pull request #7515 from vatsalgosar/BAEL-3115

BAEL-3115
This commit is contained in:
rpvilao 2019-08-11 14:48:17 +02:00 committed by GitHub
commit 32127cc5b5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 87 additions and 0 deletions

View File

@ -0,0 +1,55 @@
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);
}
}