feat: add gcd

This commit is contained in:
2025-07-22 23:42:05 +08:00
parent df4fc050b5
commit c803f805b0
2 changed files with 19 additions and 0 deletions

View File

@@ -46,6 +46,16 @@ public class MathUtil {
return v.add(BigDecimal.valueOf(nums[0])); 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の平方根計算 // Newton-Raphson法によるBigDecimalの平方根計算
public static BigDecimal sqrt(BigDecimal n, int scale) { public static BigDecimal sqrt(BigDecimal n, int scale) {
if (n.compareTo(BigDecimal.ZERO) < 0) { if (n.compareTo(BigDecimal.ZERO) < 0) {

View File

@@ -4,6 +4,7 @@ import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode; import java.math.RoundingMode;
public class MathUtilTest { public class MathUtilTest {
@@ -66,4 +67,12 @@ public class MathUtilTest {
MathUtil.sqrt(BigDecimal.valueOf(10), 100) 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)));
}
} }