【问题标题】:561 returns true on Fermat test561 在 Fermat 测试中返回 true
【发布时间】:2017-11-26 20:33:43
【问题描述】:

我发现了这个用于测试素数的费马算法,我发现它并不总是对卡迈克尔数(例如 561)返回 true。我试图找到问题,但我找不到算法有什么问题。可能是什么问题?

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

public class FermatTest {

    private final static Random rand = new Random();

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

    public static String checkPrime(BigInteger n, int maxIterations)
    {
        if (n.equals(BigInteger.ONE))
            return "is composite";

        for (int i = 0; i < maxIterations; i++)
        {
            BigInteger a = getRandomFermatBase(n); //generate random a
            a = a.modPow(n.subtract(BigInteger.ONE), n); //a^(p-1) mod p

            if (!a.equals(BigInteger.ONE)) // not equals 1
                return "is composite";
        }
        return "is probably prime";
    }

    public static void main(String[] args)
    {
        long start = System.nanoTime();
        BigInteger n = new BigInteger("561");
        System.out.println(n + " " + checkPrime(n , 20));
        float time = System.nanoTime() - start;
        System.out.println("Time: " + (long) time + " nanoseconds");
        time = time / (1000000000);
        System.out.println("Time: " + time + " seconds");
    }
}

【问题讨论】:

标签: java algorithm primes


【解决方案1】:

您自己发现了问题。对于所有可能的碱基,有一些数字,即 Carmichael 数字,被费马检验错误地标记为素数。这只是数论中的一个事实。您将需要一个不同的测试来区分数字是素数还是合数。

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 1970-01-01
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    相关资源
    最近更新 更多