feat: add gcd
This commit is contained in:
@@ -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) {
|
||||||
|
|||||||
@@ -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)));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user