Java中的 BigInteger isProbablePrime() 方法及示例
Java.math.BigInteger.isProbablePrime(int certainty)方法用于判断此 BigInteger 是否可能是素数,或者它是否肯定是复合数。此方法在调用此方法的当前 BigInteger 上检查素数或复合数,并返回一个布尔值。如果这个 BigInteger 可能是素数,它返回 true,如果它肯定是复合的,则返回 false。如果确定性 <= 0,则返回 true。
句法:
public boolean isProbablePrime(int certainty)
参数:此方法接受强制性参数确定性,这是对用户可接受的不确定性的度量。这是因为 BigInteger 是一个非常非常大的数字,并且准确地确定它是否是素数非常困难且昂贵。因此,可以说这个方法根据一个阈值(1-1/2确定性)检查这个 BigInteger 的素数。
返回值:此方法返回一个布尔值,说明此 BigInteger 是否为素数。如果这个 BigInteger 可能是素数,它返回 true,如果它肯定是复合的,则返回 false。
下面的程序用于说明 BigInteger 的 isProbablePrime() 方法。
示例 1:
// Java program to demonstrate
// isProbablePrime() method of BigInteger
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
// Boolean variable to store the result
boolean result;
// Creates one BigInteger object
BigInteger a
= new BigInteger(
"95848961698036841689418631330196");
// When certainty is one,
// it will check number for prime or composite
result = a.isProbablePrime(1);
System.out.println(a.toString()
+ " with certainty 1 "
+ result);
// When certainty is zero,
// it is always true
result = a.isProbablePrime(0);
System.out.println(a.toString()
+ " with certainty 0 "
+ result);
// When certainty is negative,
// it is always true
result = a.isProbablePrime(-1);
System.out.println(a.toString()
+ " with certainty -1 "
+ result);
}
}
输出:
95848961698036841689418631330196 with certainty 1 false
95848961698036841689418631330196 with certainty 0 true
95848961698036841689418631330196 with certainty -1 true
示例 2:
// Java program to demonstrate
// isProbablePrime() method of BigInteger
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
// Boolean variable to store the result
boolean result;
// Creates one BigInteger object
BigInteger a
= new BigInteger(
"654561561356879113561");
// When certainty is one,
// it will check number for prime or composite
result = a.isProbablePrime(1);
System.out.println(a.toString()
+ " with certainty 1 "
+ result);
// When certainty is zero,
// it is always true
result = a.isProbablePrime(0);
System.out.println(a.toString()
+ " with certainty 0 "
+ result);
// When certainty is negative,
// it is always true
result = a.isProbablePrime(-1);
System.out.println(a.toString()
+ " with certainty -1 "
+ result);
}
}
输出:
654561561356879113561 with certainty 1 false
654561561356879113561 with certainty 0 true
654561561356879113561 with certainty -1 true
参考: https://docs.oracle.com/javase/9/docs/api/ Java/math/BigInteger.html#isProbablePrime(int)