diff --git a/src/main/java/me/hatter/math/util/MathUtil.java b/src/main/java/me/hatter/math/util/MathUtil.java index 31b1183..27bd34c 100644 --- a/src/main/java/me/hatter/math/util/MathUtil.java +++ b/src/main/java/me/hatter/math/util/MathUtil.java @@ -46,6 +46,16 @@ public class MathUtil { return v.add(BigDecimal.valueOf(nums[0])); } + // https://oi-wiki.org/math/number-theory/gcd/ + public static BigInteger gcd(BigInteger a, BigInteger b) { + while (b.compareTo(BigInteger.ZERO) != 0) { + BigInteger tmp = a; + a = b; + b = tmp.mod(b); + } + return a; + } + // Newton-Raphson法によるBigDecimalの平方根計算 public static BigDecimal sqrt(BigDecimal n, int scale) { if (n.compareTo(BigDecimal.ZERO) < 0) { diff --git a/src/test/java/me/hatter/math/util/MathUtilTest.java b/src/test/java/me/hatter/math/util/MathUtilTest.java index 7571507..44fe142 100644 --- a/src/test/java/me/hatter/math/util/MathUtilTest.java +++ b/src/test/java/me/hatter/math/util/MathUtilTest.java @@ -4,6 +4,7 @@ import org.junit.Assert; import org.junit.Test; import java.math.BigDecimal; +import java.math.BigInteger; import java.math.RoundingMode; public class MathUtilTest { @@ -66,4 +67,12 @@ public class MathUtilTest { MathUtil.sqrt(BigDecimal.valueOf(10), 100) ); } + + @Test + public void testGcd() { + Assert.assertEquals(BigInteger.valueOf(1), MathUtil.gcd(BigInteger.valueOf(1), BigInteger.valueOf(3))); + Assert.assertEquals(BigInteger.valueOf(1), MathUtil.gcd(BigInteger.valueOf(3), BigInteger.valueOf(7))); + Assert.assertEquals(BigInteger.valueOf(4), MathUtil.gcd(BigInteger.valueOf(12), BigInteger.valueOf(8))); + Assert.assertEquals(BigInteger.valueOf(1), MathUtil.gcd(BigInteger.valueOf(7), BigInteger.valueOf(11))); + } }