## Baby Steps, Giant Steps

### May 6, 2016

In a previous exercise we discussed the discrete logarithm problem, which is to compute the exponent *y* in the expression *x ^{y}* ≡

*n*(mod

*m*), given

*x*,

*n*, and

*m*; the modulus

*m*is usually taken as prime. Today we look at an algorithm, known as baby steps, giant steps, that was developed by Daniel Shanks in 1971:

1. Compute limits:

*b* = ⌈ √*m* ⌉

*h* = (*x*^{−1})^{b}

2. Construct lists:

*A* = { *x ^{i}* :

*i*= 0, 1, …,

*b*− 1 } // giant steps

*B* = { *n h ^{j}* :

*j*= 0, 1, …,

*b*− 1 } // baby steps

3. Sort and find intersection:

Sort the lists *A* and *B*

Find an intersection, say *x ^{i}* =

*n h*

^{j}Return *y* = *i* + *j b*

Since *m* is prime, there must be some *y* ∈ [0, *m*) for which *x*^{y} ≡ *n* (mod *m*). Write *y* = *i* + *j b*, where *b* = ⌈ √*m* ⌉. Since *y* must exist, so too *i* (which counts the giant steps) and *j* (which counts the baby steps) must exist, and there must be an intersection between the baby steps and the giant steps.

Time complexity is obviously O(sqrt *m*), which beats the O(*m*) time complexity of the brute-force algorithm of the previous exercise. There are better algorithms for computing discrete logarithms, which we will study in future exercises.

Your task is to write a program that calculates discrete logarithms using the baby steps, giant steps algorithm. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Nice algorithm. Here’s a Python version: essentially we are precomputing values of g^n at intervals of s in the range [0..p-1): this can be done independently of the value whose logarithm we are after (so that can be done in another function that scans backwards from the desired value until it hits a precomputed value). The precise size of the interval s isn’t important for correctness – if s = 1, then we are precomputing everything, if s = p-1 we are precomputing nothing and our algorithm is just a linear scan as before. With s approximately equal to the square root of p, execution time is optimal for calculating a single logarithm. dlog might fail if g isn’t a primitive root (ie. a generator of the group):

[…] studied discrete logarithms in two previous exercises. Today we look at a third algorithm for computing discrete algorithms, invented by John Pollard in […]