【问题标题】:Fermat's primality test and Carmichael number费马素数检验和卡迈克尔数
【发布时间】:2017-01-03 22:38:33
【问题描述】:

我在玩素数和费马小定理。我读到了关于 Carmichael 的数字,他们应该通过测试。问题是,当我测试它并使用两种不同的条件时,它应该以相同的结果结束,但事实并非如此。

代码:

import java.math.BigInteger;

public class FermatTest {
    public static boolean passesAllFermatTests(BigInteger n) {
        BigInteger testValue = BigInteger.ONE;

        while (testValue.compareTo(n) == -1) {
            if (!passesFermatTest(n, testValue)) {
                return false;
            }
            testValue = testValue.add(BigInteger.ONE);
        }
        return true;
    }

    public static boolean passesFermatTest(BigInteger n, BigInteger a) {
        //if( !a.modPow(n.subtract(BigInteger.ONE), n).equals(BigInteger.ONE)) {
        if(! a.modPow(n, n).equals(a)) {
            return false;
        }

        return true;
    }

    public static void main(String[] args) {
        System.out.println(passesAllFermatTests(BigInteger.valueOf((long) 561)));
    }
}

当我在这个条件下运行它时,它返回 true(通过它)。如果我使用注释条件运行它,它会返回 false。它应该是一样的,不是吗?我的代码有错误还是我误解了什么?

【问题讨论】:

    标签: java math


    【解决方案1】:

    问题是当a = 3时,你的注释条件返回false,这是因为3和561不是互质的!卡迈克尔数要求 gcd(a,n) = 1(请参考维基百科:https://en.wikipedia.org/wiki/Carmichael_number)。

    所以在你的程序中,在应用注释条件之前,你应该首先检查“a”和“n”是相对质数。

    【讨论】:

      猜你喜欢
      • 2020-09-10
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 2013-03-03
      • 2020-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多