代码之家  ›  专栏  ›  技术社区  ›  Donald T

大整数到大整数的幂

  •  2
  • Donald T  · 技术社区  · 14 年前

    我试图使用biginger类在Java中实现Fermat、Miller-Rabin或AKS算法。

    Fermat test 实现,但BigInteger类不允许将BigInteger取为BigInteger的幂(只能将BigInteger取为原始整数的幂)。 有办法解决这个问题吗?

    有问题的行在我的代码中表示:

    public static boolean fermatPrimalityTest(BigInteger n)
    {
        BigInteger a;
        Random rand = new Random();
        int maxIterations = 100000;
    
        for (int i = 0; i < maxIterations; i++) {
            a = new BigInteger(2048, rand);
    
            // PROBLEM WITH a.pow(n) BECAUSE n IS NOT A BigInteger
            boolean test = ((a.pow(n)).minus(BigInteger.ONE)).equals((BigInteger.ONE).mod(n));
    
            if (!test)
                return false;
        }
    
        return true;
    }
    
    3 回复  |  直到 14 年前
        1
  •  5
  •   Alan Krueger    14 年前

    我想 BigInteger.modPow 可能是你要找的。注意Fermat测试中的“mod m”。

        2
  •  1
  •   Jonathan    14 年前

    BigInteger.isProbablePrime() . 不知道是哪一个,你得看看来源。

    2^100 = 2^50 * 2^50 . 所以把你的 BigInteger 动力循环直到你用完为止。但你确定你不是有意用 BigInteger.modPow() ,这需要 s?根据你的测试,看起来你是。

        3
  •  0
  •   Eugene Kuleshov    14 年前

    您必须实现自己的pow()方法。以BigInteger.pow()的源代码为起点。