BigInt是PRrime测试,更优雅的解决方案?

时间:2013-01-25 20:38:14

标签: scala biginteger

这是为isPrime个对象表达BigInt函数的最优雅方式吗?

这是我对常规整数的看法:

  def isPrimeForInt(n: Int): Boolean = {
    val ceiling = math.sqrt(n.toDouble).toInt
    (2 until ceiling) forall (x => n % x != 0)
  }

以下是BigInts的内容:

  def isPrimeForBigInt(n: BigInt): Boolean = {
    def ceiling: BigInt = {
      def f(a: BigInt): Stream[BigInt] = a #:: f(a+1)
      f(BigInt(1)).dropWhile(_.pow(2) < n)(0)
    }
    Range.BigInt(BigInt(2), ceiling , BigInt(1)) forall (x => n % x != 0)
  }

2 个答案:

答案 0 :(得分:1)

您在第一个示例中更改Int的{​​{1}}。你为什么要重写它?

答案 1 :(得分:1)

这是BigInts的primality检查器:

private static Boolean isSpsp(BigInteger n, BigInteger a)
{
    BigInteger two = BigInteger.valueOf(2);
    BigInteger n1 = n.subtract(BigInteger.ONE);
    BigInteger d = n1;
    int s = 0;

    while (d.mod(two).equals(BigInteger.ZERO))
    {
        d = d.divide(two);
        s += 1;
    }

    BigInteger t = a.modPow(d, n);

    if (t.equals(BigInteger.ONE) || t.equals(n1))
    {
        return true;
    }

    while (--s > 0)
    {
        t = t.multiply(t).mod(n);
        if (t.equals(n1))
        {
            return true;
        }
    }

    return false;
}

public static Boolean isPrime(BigInteger n)
{
    Random r = new Random();
    BigInteger two = BigInteger.valueOf(2);
    BigInteger n3 = n.subtract(BigInteger.valueOf(3));
    BigInteger a;
    int k = 25;

    if (n.compareTo(two) < 0)
    {
        return false;
    }

    if (n.mod(two).equals(BigInteger.ZERO))
    {
        return n.equals(two);
    }

    while (k > 0)
    {
        a = new BigInteger(n.bitLength(), r).add(two);
        while (a.compareTo(n) >= 0)
        {
            a = new BigInteger(n.bitLength(), r).add(two);
        }

        if (! isSpsp(n, a))
        {
            return false;
        }

        k -= 1;
    }

    return true;
}

您可以在我的Programming with Prime Numbers文章中了解更多相关信息。

相关问题