为什么java的BigInteger gcd和modInverse这么慢?

时间:2017-01-07 02:19:37

标签: java biginteger greatest-common-divisor

我正在尝试使用java.math.BigInteger 对于一些精确的整数矩阵计算,其中标量值达到数百万位。 我注意到一些内置的BigInteger操作出乎意料地非常慢 - 特别是gcd的一些情况,以及更多modInverse的情况。 看来我可以更快地实现我自己的这些函数版本。

我写了一个打印计算时间的程序 gcd(10 ^ n-3,10 ^ n)用于增加n的值达到一百万左右, 使用内置gcd或我自己的简单替代实现:

private static java.math.BigInteger myGcd(java.math.BigInteger a, java.math.BigInteger b)
{
    a = a.abs();
    b = b.abs();
    while (true)
    {
        if (b.signum() == 0) return a;
        a = a.mod(b);
        if (a.signum() == 0) return b;
        b = b.mod(a);
    }
} // myGcd

我在ubuntu linux下使用java 8运行它, 运行时版本1.8.0_111-8u111-b14-2ubuntu0.16.04.2-b14。 在具有java运行时1.8.0_92的macbook上,时间相对大致相似。

内置gcd大致是二次方的:

# numDigits seconds
1 0.000005626
2 0.000008172
4 0.000002852
8 0.000003097
16 0.000019158
32 0.000026365
64 0.000058330
128 0.000488692
256 0.000148674
512 0.007579581
1024 0.001199623
2048 0.001296036
4096 0.021341193
8192 0.024193484
16384 0.093183709
32768 0.233919912
65536 1.165671857
131072 4.169629967
262144 16.280159394
524288 67.685927438
1048576 259.500887989

我的情况大致是线性的(对于所描述的情况;是的,我知道在最坏的情况下它必须是二次方的):

# numDigits seconds
1 0.000002845
2 0.000002667
4 0.000001644
8 0.000001743
16 0.000032751
32 0.000008616
64 0.000014859
128 0.000009440
256 0.000011083
512 0.000014031
1024 0.000021142
2048 0.000036936
4096 0.000071258
8192 0.000145553
16384 0.000243337
32768 0.000475620
65536 0.000956935
131072 0.002290251
262144 0.003492482
524288 0.009635206
1048576 0.022034768

请注意,对于所描述的案例的百万位数,内置gcd需要超过10000 与我的一样长:259秒与.0220秒。

内置gcd函数是否还在执行欧几里得算法之外的其他功能?为什么呢?

我对内置modInverse与我自己的实现有类似的时间 使用扩展的欧几里德算法(此处未显示)。 内置modInverse在内置gcd的情况下表现不佳, 例如当a是一个像2,3,4这样的小数字时,......和b很大。

以下是上述数据的三个图(两个不同的线性比例,然后是对数比例):

linear scale small linear scale large log scale

这是节目列表:

/*
  Benchmark builtin java.math.BigInteger.gcd vs. a simple alternative implementation.
  To run:
    javac BigIntegerBenchmarkGcd.java
    java BigIntegerBenchmarkGcd mine > OUT.gcd.mine
    java BigIntegerBenchmarkGcd theirs > OUT.gcd.theirs

    gnuplot
      set title "Timing gcd(a=10^n-3, b=10^n)"
      set ylabel "Seconds"
      set xlabel "Number of digits"
      unset log
      set yrange [0:.5]
      #set terminal png size 512,384 enhanced font "Helvetica,10"
      #set output 'OUT0.gcd.png'
      plot [1:2**20] "OUT.gcd.theirs" with linespoints title "a.gcd(b)", "OUT.gcd.mine" with linespoints title "myGcd(a,b)"
      #set output 'OUT1.gcd.png'
      unset yrange; replot
      #set output 'OUT2.gcd.png'
      set log; replot
*/
class BigIntegerBenchmarkGcd
{
    // Simple alternative implementation of gcd.
    // More than 10000 times faster than the builtin gcd for a=10^1000000-3, b=10^1000000.
    private static java.math.BigInteger myGcd(java.math.BigInteger a, java.math.BigInteger b)
    {
        a = a.abs();
        b = b.abs();
        while (true)
        {
            if (b.signum() == 0) return a;
            a = a.mod(b);
            if (a.signum() == 0) return b;
            b = b.mod(a);
        }
    } // myGcd

    // Make sure myGcd(a,b) gives the same answer as a.gcd(b) for small values.
    private static void myGcdConfidenceTest()
    {
        System.err.print("Running confidence test... ");
        System.err.flush();
        for (int i = -10; i < 10; ++i)
        for (int j = -10; j < 10; ++j)
        {
            java.math.BigInteger a = java.math.BigInteger.valueOf(i);
            java.math.BigInteger b = java.math.BigInteger.valueOf(j);
            java.math.BigInteger theirAnswer = a.gcd(b);
            java.math.BigInteger myAnswer = myGcd(a, b);
            if (!myAnswer.equals(theirAnswer)) {
                throw new AssertionError("they say gcd("+a+","+b+") is "+theirAnswer+", I say it's "+myAnswer);
            }
        }
        System.err.println("passed.");
    }

    public static void main(String args[])
    {
        boolean useMine = false;
        if (args.length==1 && args[0].equals("theirs"))
            useMine = false;
        else if (args.length==1 && args[0].equals("mine"))
            useMine = true;
        else
        {
            System.err.println("Usage: BigIntegerBenchmarkGcd theirs|mine");
            System.exit(1);
        }

        myGcdConfidenceTest();

        System.out.println("# numDigits seconds");
        for (int numDigits = 1; numDigits <= (1<<20); numDigits *= 2)
        {
            java.math.BigInteger b = java.math.BigInteger.TEN.pow(numDigits);
            java.math.BigInteger a = b.subtract(java.math.BigInteger.valueOf(3));

            System.out.print(numDigits+" ");
            System.out.flush();

            long t0nanos = System.nanoTime();
            java.math.BigInteger aInverse = useMine ? myGcd(a, b)
                                                    : a.gcd(b);
            long t1nanos = System.nanoTime();

            double seconds = (t1nanos-t0nanos)/1e9;
            System.out.println(String.format("%.9f", seconds));
        }
    } // main
} // class BigIntegerBenchmarkGcd

1 个答案:

答案 0 :(得分:0)

对于比特长度相差不超过1的BigInteger aba.gcd(b)使用binary GCD algorithm进行O(n)减法和移位(其中n是整数的位长度)。它的运行时间很弱地取决于输入整数是什么,例如,它们彼此之间的距离。在你的情况下,b - a = 3,并且已经在你的欧几里德算法b = b.mod(a)的实现的第一次迭代中是3.所以算法的步数不依赖于整数&#39;长度,并立即退出。

BTW,10 ^ n总是与10 ^ n - 3相互作用。

相关问题