Java.math.BigInteger.isProbablePrime()方法範例


java.math.BigInteger.isProbablePrime(int certainty) 如果此BigInteger可能是素數,如果其絕對複合返回false。如果確定是≤0,則返回true。

宣告

以下是java.math.BigInteger.isProbablePrime()方法的宣告

public boolean isProbablePrime(int certainty)

引數

  • certainty - 這一措施的呼叫者能容忍的不確定性:如果呼叫返回true,則此BigInteger是素數超過概率(1 - 1/2確定性)。此方法的執行時間正比於該引數的值。

返回值

如果此BigInteger可能是素數,如果其絕對複合此方法則返回true。

異常

  • NA

例子

下面的例子顯示math.BigInteger.isProbablePrime()方法的用法

package com.yiibai;

import java.math.*;

public class BigIntegerDemo {

public static void main(String[] args) {

        // create 3 BigInteger objects
	BigInteger bi1, bi2, bi3;

	// create 3 Boolean objects
	Boolean b1, b2, b3;

	// assign values to bi1, bi2
	bi1 = new BigInteger("7");
	bi2 = new BigInteger("9");

	// perform isProbablePrime on bi1, bi2
	b1 = bi1.isProbablePrime(1);
	b2 = bi2.isProbablePrime(1);
	b3 = bi2.isProbablePrime(-1);

	String str1 = bi1+ " is prime with certainity 1 is " +b1;
	String str2 = bi2+ " is prime with certainity 1 is " +b2;
	String str3 = bi2+ " is prime with certainity -1 is " +b3;

	// print b1, b2, b3 values
	System.out.println( str1 );
	System.out.println( str2 );
	System.out.println( str3 );
    }
}

讓我們編譯和執行上面的程式,這將產生以下結果:

7 is prime with certainity 1 is true
9 is prime with certainity 1 is false
9 is prime with certainity -1 is true