Java:获得最大的公约数 [英] Java: get greatest common divisor

查看:126
本文介绍了Java:获得最大的公约数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到 BigInteger 存在这样的函数,即 的BigInteger#GCD 。 Java中是否还有其他函数可用于其他类型( int long Integer )?这似乎是有道理的 java.lang.Math.gcd (带有各种重载),但它不存在。是在其他地方吗?

I have seen that such a function exists for BigInteger, i.e. BigInteger#gcd. Are there other functions in Java which also work for other types (int, long or Integer)? It seems this would make sense as java.lang.Math.gcd (with all kinds of overloads) but it is not there. Is it somewhere else?

(请不要将此问题与我如何自己实施这一问题混淆,请! )

(Don't confuse this question with "how do I implement this myself", please!)

推荐答案

对于int和long,作为原语,不是真的。对于整数,可能有人写了一个。

For int and long, as primitives, not really. For Integer, it is possible someone wrote one.

由于BigInteger的是(数学/功能)INT的超集,整数,长,长,如果您需要使用这些类型,将它们转换为BigInteger,执行GCD,然后将结果转换回来。

Given that BigInteger is a (mathematical/functional) superset of int, Integer, long, and Long, if you need to use these types, convert them to a BigInteger, do the GCD, and convert the result back.

private static int gcdThing(int a, int b) {
    BigInteger b1 = new BigInteger(""+a); // there's a better way to do this. I forget.
    BigInteger b2 = new BigInteger(""+b);
    BigInteger gcd = b1.gcd(b2);
    return gcd.intValue();
}

更好的方式:

private static int gcdThing(int a, int b) {
    BigInteger b1 = BigInteger.valueOf(a);
    BigInteger b2 = BigInteger.valueOf(b);
    BigInteger gcd = b1.gcd(b2);
    return gcd.intValue();
}

这篇关于Java:获得最大的公约数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆