Как оптимизировать этот алгоритм. Два словаря и поиск определенного значения - PullRequest
0 голосов
/ 21 сентября 2011

У меня есть 2 словаря.Я пытаюсь оптимизировать этот код, чтобы он работал как можно быстрее.

edit: Извините, это решение для алгоритма Step Shiant Baby Giant Step
Algorithm:

Given b = a^x (mod p)
First choose n, such that n^2 >= p-1
Then create 2 lists:
    1. a^j (mod p) for 0 <= j < n
    2. b*(a(inverse)^n)^k for 0 <= k < n
Finally look for a match between the 2 lists.


public static BigInteger modInverse(BigInteger a, BigInteger n)
{
    BigInteger i = n, v = 0, d = 1;
    while (a > 0)
    {
        BigInteger t = i / a, x = a;
        a = i % x;
        i = x;
        x = d;
        d = v - t * x;
        v = x;
    }
    v %= n;
    if (v < 0) v = (v + n) % n;
    return v;
}

static int Main()
{
    BigInteger r = 92327518017225,
               rg,
               temp,
               two=2,
               tm, 
               n = ((BigInteger)Math.Sqrt(247457076132467-1))+1, 
               mod = 247457076132467;
    Dictionary<int, BigInteger> b = new Dictionary<int, BigInteger>();
    Dictionary<int, BigInteger> g = new Dictionary<int, BigInteger>();
    temp = modInverse(two, mod);
    temp = BigInteger.ModPow(temp, n, mod);
    for (int j = 0; (BigInteger)j < n; j++)
    {
        rg = r * BigInteger.ModPow(temp, j, mod);
        g.Add(j, rg);
    }
    for (int i = 0; (BigInteger)i < n ; i++)
    {
        tm = BigInteger.ModPow(2, i, mod);
        foreach (KeyValuePair<int, BigInteger> d in g)
        {
            if (d.Value.Equals(tm))
            {
                Console.WriteLine("j={0}   B*t^j(mod m) = {1}",d.Key,d.Value);
                Console.WriteLine("a^"+i+" = "+tm);
            }
        }
        b.Add(i,tm);
    }
    Console.ReadKey();
    return 0;
}

1 Ответ

1 голос
/ 21 сентября 2011

Одной из простых оптимизаций является переключение словаря g так, чтобы BigInteger был ключом

Затем вы можете использовать .ContainsKey для поиска вместо циклического поиска, что будет намного быстрее

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...