java - 费马素性测试的实现

标签 java math primes biginteger

谁愿意帮我做作业?

我正在尝试实现 Fermat's primality test在 Java 中使用 BigIntegers。我的实现如下,但不幸的是它不起作用。有什么想法吗?

public static boolean checkPrime(BigInteger n, int maxIterations)
{
    if (n.equals(BigInteger.ONE))
        return false;

    BigInteger a;
    Random rand = new Random();

    for (int i = 0; i < maxIterations; i++)
    {
        a = new BigInteger(n.bitLength() - 1, rand);
        a = a.modPow(n.subtract(BigInteger.ONE), n);

        if (!a.equals(BigInteger.ONE))
            return false;
    }

    return true;
}

我是 BigIntegers 新手。

谢谢!

最佳答案

您对特定 BigInteger 构造函数的使用是合理的,但您应该使用 rejection method选择费马基 a.以下是对类中方法的轻微修改,该类也仅使用一个 Random 对象:

import java.math.BigInteger;
import java.util.Random;

public class FermatTestExample
{

    private final static Random rand = new Random();

    private static BigInteger getRandomFermatBase(BigInteger n)
    {
        // Rejection method: ask for a random integer but reject it if it isn't
        // in the acceptable set.

        while (true)
        {
            final BigInteger a = new BigInteger (n.bitLength(), rand);
            // must have 1 <= a < n
            if (BigInteger.ONE.compareTo(a) <= 0 && a.compareTo(n) < 0)
            {
                return a;
            }
        }
    }

    public static boolean checkPrime(BigInteger n, int maxIterations)
    {
        if (n.equals(BigInteger.ONE))
            return false;

        for (int i = 0; i < maxIterations; i++)
        {
            BigInteger a = getRandomFermatBase(n);
            a = a.modPow(n.subtract(BigInteger.ONE), n);

            if (!a.equals(BigInteger.ONE))
                return false;
        }

        return true;
    }

    public static void main(String[] args)
    {
        System.out.printf("checkprime(2) is %b%n", checkPrime(BigInteger.valueOf(2L), 20));
        System.out.printf("checkprime(5) is %b%n", checkPrime(BigInteger.valueOf(5L), 20));
        System.out.printf("checkprime(7) is %b%n", checkPrime(BigInteger.valueOf(7L), 20));
        System.out.printf("checkprime(9) is %b%n", checkPrime(BigInteger.valueOf(9L), 20));
    }
}

关于java - 费马素性测试的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4027225/

相关文章:

c++ - 反模的奇怪行为

Python – 让一个变量既是 int 又是 str

java - 将鼠标悬停在 JButton 上并显示一条消息

math - Perl 6中列表的所有子集

javascript - 如何修复 NaN 错误 - 参数值不进行加、减、除或乘 - 在 JavaScript 中

c - 用 C 代码实现哥德巴赫猜想

java - Android SDK - Eclipse - 如何在多个类中使用一段代码

java - 使用 Java 的 ByteBuffer 读取百万条消息

java - 用Java写一个mode方法找到数组中出现频率最高的元素

c# - 如何使用HashSet作为数学集合?