优化Karatsuba实施

时间:2010-02-02 19:47:05

标签: c# biginteger

所以,我正在尝试改进.net 4的BigInteger类提供的一些操作,因为操作看起来是二次的。我做了一个粗略的Karatsuba实现,但它仍然比我预期的慢。

主要问题似乎是BigInteger没有提供计算位数的简单方法,因此,我必须使用BigInteger.Log(...,2)。根据Visual Studio,大约80-90%的时间用于计算对数。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace Test
{
    class Program
    {
        static BigInteger Karatsuba(BigInteger x, BigInteger y)
        {
            int n = (int)Math.Max(BigInteger.Log(x, 2), BigInteger.Log(y, 2));
            if (n <= 10000) return x * y;

            n = ((n+1) / 2);

            BigInteger b = x >> n;
            BigInteger a = x - (b << n);
            BigInteger d = y >> n;
            BigInteger c = y - (d << n);

            BigInteger ac = Karatsuba(a, c);
            BigInteger bd = Karatsuba(b, d);
            BigInteger abcd = Karatsuba(a+b, c+d);

            return ac + ((abcd - ac - bd) << n) + (bd << (2 * n));
        }

        static void Main(string[] args)
        {
            BigInteger x = BigInteger.One << 500000 - 1;
            BigInteger y = BigInteger.One << 600000 + 1;
            BigInteger z = 0, q;

            Console.WriteLine("Working...");
            DateTime t;

            // Test standard multiplication
            t = DateTime.Now;
            z = x * y;
            Console.WriteLine(DateTime.Now - t);

            // Test Karatsuba multiplication
            t = DateTime.Now;
            q = Karatsuba(x, y);
            Console.WriteLine(DateTime.Now - t);

            // Check they're equal
            Console.WriteLine(z == q);

            Console.Read();
        }
    }
}

那么,我该怎么做才能加快速度呢?

1 个答案:

答案 0 :(得分:12)

为什么要计算所有位?

在vb中我这样做:

<Runtime.CompilerServices.Extension()> _
Function BitLength(ByVal n As BigInteger) As Integer
    Dim Data() As Byte = n.ToByteArray
    Dim result As Integer = (Data.Length - 1) * 8
    Dim Msb As Byte = Data(Data.Length - 1)
    While Msb
        result += 1
        Msb >>= 1
    End While
    Return result
End Function

在C#中它将是:

public static int BitLength(this BigInteger n)
{
    byte[] Data = n.ToByteArray();
    int result = (Data.Length - 1) * 8;
    byte Msb = Data[Data.Length - 1];
    while (Msb != 0) {
        result += 1;
        Msb >>= 1;
    }
    return result;
}

...最后

    static BigInteger Karatsuba(BigInteger x, BigInteger y)
    {
        int n = (int)Math.Max(x.BitLength(), y.BitLength());
        if (n <= 10000) return x * y;

        n = ((n+1) / 2);

        BigInteger b = x >> n;
        BigInteger a = x - (b << n);
        BigInteger d = y >> n;
        BigInteger c = y - (d << n);

        BigInteger ac = Karatsuba(a, c);
        BigInteger bd = Karatsuba(b, d);
        BigInteger abcd = Karatsuba(a+b, c+d);

        return ac + ((abcd - ac - bd) << n) + (bd << (2 * n));
    }

调用扩展方法可能会减慢速度,所以这可能会更快:

int n = (int)Math.Max(BitLength(x), BitLength(y));

仅供参考:使用位长方法,您还可以比BigInteger方法快得多地计算日志的近似值。

bits = BitLength(a) - 1;
log_a = (double)i * log(2.0);

就访问BigInteger结构的内部UInt32数组而言,这是一个黑客攻击。

导入反射命名空间

Private Shared ArrM As MethodInfo
Private Shard Bits As FieldInfo
Shared Sub New()
    ArrM = GetType(System.Numerics.BigInteger).GetMethod("ToUInt32Array", BindingFlags.NonPublic Or BindingFlags.Instance)
    Bits = GetType(System.Numerics.BigInteger).GetMember("_bits", BindingFlags.NonPublic Or BindingFlags.Instance)(0)

End Sub
<Extension()> _
Public Function ToUInt32Array(ByVal Value As System.Numerics.BigInteger) As UInteger()
    Dim Result() As UInteger = ArrM.Invoke(Value, Nothing)
    If Result(Result.Length - 1) = 0 Then
        ReDim Preserve Result(Result.Length - 2)
    End If
    Return Result
End Function

然后你可以得到大整数的底层UInteger()为

 Dim Data() As UInteger = ToUInt32Array(Value)
 Length = Data.Length 

或替代

Dim Data() As UInteger = Value.ToUInt32Array()

请注意,_bits fieldinfo可用于直接访问BigInteger结构的基础UInteger()_bits字段。这比调用ToUInt32Array()方法更快。但是,当BigInteger B&lt; = UInteger.MaxValue _bits没什么的时候。我怀疑当BigInteger符合32位(机器大小)字的大小时,MS返回作为优化,返回使用本机数据类型执行正常的机器字算术。

我也无法使用_bits.SetValue(B,Data()),因为您通常可以使用反射。要解决这个问题,我使用具有开销的BigInteger(bytes()b)构造函数。在c#中,您可以使用不安全的指针操作将UInteger()强制转换为Byte()。由于VB中没有指针操作,我使用Buffer.BlockCopy。当以这种方式访问​​数据时,重要的是要注意,如果设置了bytes()数组的MSB,则MS将其解释为负数。我希望他们制作一个带有单独符号字段的构造函数。字数组是添加一个额外的0字节以取消选中MSB

另外,在平方时你可以进一步提高

 Function KaratsubaSquare(ByVal x As BigInteger)
    Dim n As Integer = BitLength(x) 'Math.Max(BitLength(x), BitLength(y))

    If (n <= KaraCutoff) Then Return x * x
    n = ((n + 1) >> 1)

    Dim b As BigInteger = x >> n
    Dim a As BigInteger = x - (b << n)
    Dim ac As BigInteger = KaratsubaSquare(a)
    Dim bd As BigInteger = KaratsubaSquare(b)
    Dim c As BigInteger = Karatsuba(a, b)
    Return ac + (c << (n + 1)) + (bd << (2 * n))

End Function

这消除了乘法算法每次递归的2次移位,2次加法和3次减法。