Guava LongMath类的方法gcd(long a,long b)返回两个参数a和b的最大公约数。
用法:
public static long gcd(long a, long b)
参数:此方法接受要查找其GCD的long类型的两个参数a和b。
返回类型:此方法返回最大的正long值,该值将传递给函数的两个参数相除。
异常:如果a为负数或b为负数,则方法gcd(long a,long b)抛出IllegalArgumentException。
注意:如果a和b均为零,则该方法返回零。
范例1:
// Java code to show implementation of
// gcd(long a, long b) method of Guava's
// LongMath class
import java.math.RoundingMode;
import com.google.common.math.LongMath;
class GFG {
// Driver code
public static void main(String args[])
{
long a1 = 14;
long b1 = 70;
// Using gcd(long a, long b) method
// of Guava's LongMath class
long ans1 = LongMath.gcd(a1, b1);
System.out.println("GCD of " + a1
+ " and " + b1
+ " is " + ans1);
long a2 = 23;
long b2 = 15;
// Using gcd(long a, long b) method
// of Guava's LongMath class
long ans2 = LongMath.gcd(a2, b2);
System.out.println("GCD of " + a2
+ " and " + b2
+ " is " + ans2);
}
}
输出:
GCD of 14 and 70 is 14 GCD of 23 and 15 is 1
范例2:
// Java code to show implementation of
// gcd(long a, long b) method of Guava's
// LongMath class
import java.math.RoundingMode;
import com.google.common.math.LongMath;
class GFG {
// Driver code
public static void main(String args[])
{
long a = -5;
long b = 15;
try {
// Using gcd(long a, long b) method
// of Guava's LongMath class
// This should throw "IllegalArgumentException"
// as a < 0
long ans = LongMath.gcd(a, b);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
java.lang.IllegalArgumentException:a (-5) must be >= 0
相关用法
- Java Guava LongMath mean(long x, long y)用法及代码示例
- Java Guava LongMath mod(long x, long m)用法及代码示例
- Java Guava LongMath pow(long b, int k)用法及代码示例
- Java Guava LongMath isPowerOfTwo(long x)用法及代码示例
- Java Guava LongMath sqrt(long x, RoundingMode mode)用法及代码示例
- Java LongMath.divide(long, long, RoundingMode)用法及代码示例
- Java LongMath.checkedAdd(long a, long b)用法及代码示例
- Java LongMath.checkedPow(long b, int k)用法及代码示例
- Java LongMath log10(long x, RoundingMode mode)用法及代码示例
- Java Guava LongMath binomial(int n, int k)用法及代码示例
- Java LongMath.checkedMultiply(int a, int b)用法及代码示例
- Java Longs.checkedSubtract(long a, long b)用法及代码示例
- Java Longs.indexOf(long[] array, long[] target)用法及代码示例
注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Java Guava | gcd(long a, long b) of LongMath Class with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。