/**************************************************************************
* Author: Isai Damier
* Title: Greatest Common Divisor
* Project: geekviewpoint
* Package: algorithms
*
* Statement:
* Find the greatest common divisor of the given numbers
*
* Sample Input: 18, 27
* Sample Output: 9
*
* Description: This function finds the greatest common
* divisor of the given numbers. The GCD of x and y is the greatest
* integer that divides both x and y evenly. For example the gcd of
* 18 and 27 is 9 because 9*3 = 27 and 9*2= 18.
*
* Technical Details: Mathematicians have found numerous techniques
* for calculating the GCD of two numbers. The present
* implementation uses the mod operator. Other implementations
* may use subtraction, for example.
*
*************************************************************************/
public int GCD(int a, int b) {
if (0 == a || 0 == b) {
return -1;
}
if (1 == a || 1 == b) {
return 1;
}
while (0 < a && 0 < b) {
if (a > b) {
a %= b;
} else {
b %= a;
}
}
return 0 == a ? b : a;
}
import org.junit.Test;
import static org.junit.Assert.*;
public class NumbersTest {
/**
* Test of GCD method, of class Numbers.
*/
@Test
public void testGCD() {
System.out.println("GCD");
Numbers greatestCommonDivisor = new Numbers();
assertEquals(8, greatestCommonDivisor.GCD(24, 16));
assertEquals(8, greatestCommonDivisor.GCD(16, 24));
assertEquals(16, greatestCommonDivisor.GCD(16, 16));
assertEquals(1, greatestCommonDivisor.GCD(13, 29));
}
}