<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-835341608950140555</id><updated>2011-07-08T03:18:44.612+02:00</updated><category term='primes'/><category term='fast fourier transform'/><category term='factorization'/><category term='digital signal processing'/><category term='general'/><category term='python'/><category term='sieving'/><category term='modular arithmetic'/><category term='number theory'/><title type='text'>Numerical Recipes</title><subtitle type='html'>&lt;p&gt;"Come the (computer) revolution, all persons found guilty of such criminal behavior will be summarily executed, and their programs won’t be!"&lt;/p&gt;
from &lt;i&gt;Numerical Recipes in C&lt;/i&gt;</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://numericalrecipes.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://numericalrecipes.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Jaime</name><uri>http://www.blogger.com/profile/02831887559711602902</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://1.bp.blogspot.com/_47tBuP0my9o/Sa6DmpICr3I/AAAAAAAAAGE/rGBLWTTlODU/S220/318462932_a2fef46344_m.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>9</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-835341608950140555.post-2873178869406001815</id><published>2009-04-30T18:10:00.004+02:00</published><updated>2009-04-30T18:26:47.804+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='general'/><title type='text'>Go West Young Man!</title><content type='html'>I have had to find it out the hard way, but blogger sucks when it comes to math blogging. It wouldn't be all that bad, were it not because on the other side of the road things are soooo very much easier. And while I will miss google analytics, the native support for latex and syntax highlighting make up for it more than enough. So I'm moving this blog to wordpress...&lt;br /&gt;&lt;br /&gt;You can find the new blog &lt;a href="http://numericalrecipes.wordpress.com/"&gt;here&lt;/a&gt;, and suscribe to the RSS feed &lt;a href="http://numericalrecipes.wordpress.com/feed/"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;For starters I have redone the much improvable first post of the series on the FFT, which I have split in two, &lt;a href="http://numericalrecipes.wordpress.com/2009/04/30/the-discrete-fourier-transform/"&gt;one on the DFT&lt;/a&gt;, &lt;a href="http://numericalrecipes.wordpress.com/2009/04/30/the-radix-2-cooley-tukey-fft-algorithm-with-decimation-in-time/"&gt;the other starting discussion on the FFT&lt;/a&gt;, plus an unconnected post on &lt;a href="http://numericalrecipes.wordpress.com/2009/04/30/computing-the-greatest-common-divisor/"&gt;computing the GCD&lt;/a&gt;...&lt;br /&gt;&lt;br /&gt;I will be moving all the content in this blog over to the new one, but have no intention of deleting anything from this one.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/835341608950140555-2873178869406001815?l=numericalrecipes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://numericalrecipes.blogspot.com/feeds/2873178869406001815/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://numericalrecipes.blogspot.com/2009/04/go-west-young-man.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/2873178869406001815'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/2873178869406001815'/><link rel='alternate' type='text/html' href='http://numericalrecipes.blogspot.com/2009/04/go-west-young-man.html' title='Go West Young Man!'/><author><name>Jaime</name><uri>http://www.blogger.com/profile/02831887559711602902</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://1.bp.blogspot.com/_47tBuP0my9o/Sa6DmpICr3I/AAAAAAAAAGE/rGBLWTTlODU/S220/318462932_a2fef46344_m.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-835341608950140555.post-25248395429328190</id><published>2009-04-16T22:30:00.025+02:00</published><updated>2009-04-19T01:22:27.911+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='digital signal processing'/><category scheme='http://www.blogger.com/atom/ns#' term='fast fourier transform'/><title type='text'>The Cooley-Tukey FFT Algorithm</title><content type='html'>I'm currently a little fed up with &lt;a href="http://numericalrecipes.blogspot.com/search/label/number%20theory"&gt;number theory&lt;/a&gt;, so its time to change topics completely. Specially since the post on &lt;a href="http://numericalrecipes.blogspot.com/2009/04/naive-integer-factorization.html"&gt;basic integer factorization&lt;/a&gt; completes what I believe is a sufficient toolkit to tackle a very cool subject: the &lt;a href="http://en.wikipedia.org/wiki/Fast_Fourier_transform"&gt;fast Fourier transform (FFT)&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;I have some mixed feelings about how does the Fourier transform qualify for the "uncomplicated complexity" rule I imposed on myself when starting this blog. There certainly is a lot of very elaborate math behind Fourier analysis, but I think that if you skip all the mathematical subtleties and dive head first into a "the Fourier transform gives you the frequencies present in the signal" type of intuitive description, the journey from the naive implementation of the &lt;a href="http://en.wikipedia.org/wiki/Discrete_Fourier_transform"&gt;discrete Fourier transform (DFT)&lt;/a&gt; to the many flavors of the FFT is a very enjoyable one, which requires only a limited amount of complication, but gentle doses of complexity. Which is exactly what I'm after...&lt;br /&gt;&lt;br /&gt;So I will take the definition of the DFT for granted, and concentrate on the algorithms to compute it efficiently. There will have to be a few more leaps of faith, but I will try to mark them clearly, so you can whisper "amen" and keep going without a second thought. Although things may unfold differently, I think there is material for about half a dozen posts. Towards the end I may devote some time to optimizing the code, with things such as avoiding recursion, or doing the calculations in place, but most of my efforts will be devoted to optimizing the math behind the code, not the code itself. So the resulting code will probably be suboptimal: if you spot a potential improvement your comments are welcome and encouraged.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;The Discrete Fourier Transform&lt;/span&gt;&lt;br /&gt;Without further explanation, we will begin by writing down the analytical expression of the DFT,&lt;br /&gt;&lt;img alt="tex: \displaystyle X_k = \sum_{n=0}^{N-1}{x_n e^{-2\pi i k n / N}}," /&gt;&lt;br /&gt;and of its corresponding inverse transform,&lt;br /&gt;&lt;img alt="tex: \displaystyle x_n = \sum_{k=0}^{N-1}{X_k e^{2\pi i k n / N}}." /&gt;&lt;br /&gt;With python's built-in support for complex arithmetic, there really isn't much mistery in turning these two formulas into two python functions, or as I have chosen, one with an &lt;code&gt;inverse&lt;/code&gt; switch:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;from __future__ import division&lt;br /&gt;import math&lt;br /&gt;import time&lt;br /&gt;&lt;br /&gt;def dft(x, inverse = False, verbose = False) :&lt;br /&gt;    t = time.clock()&lt;br /&gt;    N = len(x)&lt;br /&gt;    inv = -1 if not inverse else 1&lt;br /&gt;    X =[0] * N&lt;br /&gt;    for k in xrange(N) :&lt;br /&gt;        for n in xrange(N) :&lt;br /&gt;            X[k] += x[n] * math.e**(inv * 2j * math.pi * k * n / N)&lt;br /&gt;        if inverse :&lt;br /&gt;            X[k] /= N&lt;br /&gt;    t = time.clock() - t&lt;br /&gt;    if verbose :&lt;br /&gt;        print "Computed","an inverse" if inverse else "a","DFT of size",N,&lt;br /&gt;        print "in",t,"sec."&lt;br /&gt;    return X&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Of course, having two nested loops of the size of the input means that computation time will grow with N&lt;sup&gt;2&lt;/sup&gt;, which is extremely inefficient.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;The Radix-2 Cooley-Tukey Algorithm with Decimation in Time&lt;/span&gt;&lt;br /&gt;How can that be improved? If the size of the input is even, we can write N = 2·M and it is possible to split the N element summation in the previous formulas into two M element ones, one over n = 2·m, another over n = 2·m + 1. By doing so, we arrive at&lt;br /&gt;&lt;img alt="tex: \displaystyle X_k = \sum_{m=0}^{M-1}{x_{2m} e^{-2\pi i \frac{m k}{M} }} + e^{-2\pi i\frac{k}{N}} \sum_{m=0}^{M-1}{x_{2m+1} e^{-2\pi i\frac{m k}{M}}}" /&gt;&lt;br /&gt;for the direct transform, and&lt;br /&gt;&lt;img style="width: 400px;" alt="tex: \displaystyle x_n = \frac{1}{2} \left(\frac{1}{M} \sum_{m=0}^{M-1}{X_{2m} e^{2\pi i \frac{m n}{M} }} + e^{2\pi i\frac{n}{N}}\frac{1}{M} \sum_{m=0}^{M-1}{X_{2m+1} e^{2\pi i\frac{m n}{M}}}\right)" /&gt;&lt;br /&gt;for the inverse.&lt;br /&gt;&lt;br /&gt;If you look carefully at this formulas, you'll notice we have just split our size N transform, be it direct or inverse, into two others of half the size, one over even indexes, the other over odd ones. The factor multiplying the second partial transform is known as a &lt;a href="http://en.wikipedia.org/wiki/Twiddle_factor"&gt;twiddle factor&lt;/a&gt;, and introduces a little overhead to the total timing, but overall we have just managed to cut the total time in half. And if the input size happens to be a power of two, we need not stop here, for as long as it is divisible by two, we can repeat the process iteratively, leading to a time of N log N.&lt;br /&gt;&lt;br /&gt;To implement this recursive approach we need to take care of a few more details, though. First, if you look at the previous formulas, variable k in the direct transform, or n in the inverse, runs all the way to N = 2·M, rather than to M, as one would expect in the standard DFT. By taking advantage of the fact that the exponential function is periodic with period 2πi, it is quite easy to show that, for k (or n) larger than M, the resulting value will be the same as the one obtained for k-M (or n-M).&lt;br /&gt;&lt;br /&gt;The other open question is at what point to stop the recursion. The simplest approach is to keep going until the input size is odd, and then call the naive DFT function. If the size happens to be a power of two, this call will not happen until the input size comes down to one. Since the DFT of a single sample signal is the same signal unchanged, that is a wasteful way of coding. But since it clarifies the logic behind the algorithm, I will leave those optimizations for a later stage.&lt;br /&gt;&lt;br /&gt;With this caveats in mind, this FFT algorithm can be coded in python as follows:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;from __future__ import division&lt;br /&gt;import math&lt;br /&gt;import time&lt;br /&gt;&lt;br /&gt;def fft_CT(x, inverse = False, verbose = False) :&lt;br /&gt;    t = time.clock()&lt;br /&gt;    N = len(x)&lt;br /&gt;    inv = -1 if not inverse else 1&lt;br /&gt;    if N % 2 :&lt;br /&gt;        return dft(x, inverse, False)&lt;br /&gt;    x_e = x[::2]&lt;br /&gt;    x_o  = x[1::2]&lt;br /&gt;    X_e = fft_CT(x_e, inverse, False)&lt;br /&gt;    X_o  = fft_CT(x_o, inverse, False)&lt;br /&gt;    X = []&lt;br /&gt;    M = N // 2&lt;br /&gt;    for k in range(M) :&lt;br /&gt;        X += [X_e[k] + X_o[k] * math.e ** (inv * 2j * math.pi * k / N)]&lt;br /&gt;    for k in range(M,N) :&lt;br /&gt;        X += [X_e[k-M] - X_o[k-M] * math.e ** (inv * 2j * math.pi * (k-M) / N)]&lt;br /&gt;    if inverse :&lt;br /&gt;        X = [j/2 for j in X]&lt;br /&gt;    t = time.clock() - t&lt;br /&gt;    if verbose :&lt;br /&gt;        print "Computed","an inverse" if inverse else "a","CT FFT of size",N,&lt;br /&gt;        print "in",t,"sec."&lt;br /&gt;    return X&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The speed gain with this approach, restricted for now to power of two sizes, are tremendous even for moderately large input sizes. For instance, a 2&lt;sup&gt;20&lt;/sup&gt; (~10&lt;sup&gt;6&lt;/sup&gt;) item input can be processed with the FFT approach in a couple of minutes, while the projected duration using the naive DFT will be more like a couple of months...&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/835341608950140555-25248395429328190?l=numericalrecipes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://numericalrecipes.blogspot.com/feeds/25248395429328190/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://numericalrecipes.blogspot.com/2009/04/cooley-turkey-fft-algorithm.html#comment-form' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/25248395429328190'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/25248395429328190'/><link rel='alternate' type='text/html' href='http://numericalrecipes.blogspot.com/2009/04/cooley-turkey-fft-algorithm.html' title='The Cooley-Tukey FFT Algorithm'/><author><name>Jaime</name><uri>http://www.blogger.com/profile/02831887559711602902</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://1.bp.blogspot.com/_47tBuP0my9o/Sa6DmpICr3I/AAAAAAAAAGE/rGBLWTTlODU/S220/318462932_a2fef46344_m.jpg'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-835341608950140555.post-2694194336765089829</id><published>2009-04-09T00:20:00.008+02:00</published><updated>2009-04-16T22:50:35.791+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='primes'/><category scheme='http://www.blogger.com/atom/ns#' term='number theory'/><category scheme='http://www.blogger.com/atom/ns#' term='python'/><category scheme='http://www.blogger.com/atom/ns#' term='factorization'/><title type='text'>Naive Integer Factorization</title><content type='html'>After three posts (&lt;a href="http://numericalrecipes.blogspot.com/2009/03/prime-numbers_04.html"&gt;1&lt;/a&gt;, &lt;a href="http://numericalrecipes.blogspot.com/2009/03/prime-numbers-2-sieving-of-erathostenes.html"&gt;2&lt;/a&gt;, &lt;a href="http://numericalrecipes.blogspot.com/2009/03/prime-numbers-3-wheel-factorization.html"&gt;3&lt;/a&gt;) on calculating prime numbers, it is probably worth putting that knowledge to a more useful task. As we will see in a near future, &lt;a href="http://en.wikipedia.org/wiki/Integer_factorization"&gt;integer factorization&lt;/a&gt;, i.e. breaking down a (composite) number into its prime factors is one such task. In purity, factoring a number n is simply decomposing it as the product of two smaller non-trivial, i.e. different from 1 and n itself, divisors. But by repeatedly factoring the divisors one will eventually come up with a unique set of primes which, when multiplied together, render the original number, or so says the &lt;a href="http://en.wikipedia.org/wiki/Fundamental_theorem_of_arithmetic"&gt;fundamental theorem of arithmetic&lt;/a&gt;... The point is, we will consider factorization a synonym of prime decomposition, be it formally correct or not.&lt;br /&gt;&lt;br /&gt;There are some very sophisticated methods to factor very large numbers, but they use a lot of extremely complex math, so I doubt they will ever find their way onto this blog. So we are going to be left with the naive, straightforward approach as our only option, although I will try to give it an efficiency boost. What is this naive approach? Trial division, of course: given a number n, we know that its smallest factor will be smaller than the square root of n, so we can simply try and see if any of those numbers divide it. No, I will not try to code that yet... If you have read the entries on determining prime numbers, it should come as no surprise that we really do not need to do trial division by all numbers smaller than the square root of n, but only by the primes within. This is a consequence of the fact that, if a composite number divides n, then each of the prime factors of that composite number will also divide n. According to the &lt;a href="http://en.wikipedia.org/wiki/Prime_number_theorem"&gt;prime number theorem&lt;/a&gt; the number of primes below x is asymptotic to x / log x. So by limiting our trials to prime numbers we can reduce the number of tests from n&lt;sup&gt;1/2&lt;/sup&gt; to something around 2 n&lt;sup&gt;1/2&lt;/sup&gt; / log n. If we rescue the &lt;code&gt;primeListSofE&lt;/code&gt; function from &lt;a href="http://numericalrecipes.blogspot.com/2009/03/prime-numbers-2-sieving-of-erathostenes.html"&gt;the post on the sieve of Erathostenes&lt;/a&gt;, a python implementation of naive factorization could look something like this...&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;from time import clock&lt;br /&gt;&lt;br /&gt;def factor(n, verbose = False) :&lt;br /&gt;    """Returns all prime factors of n, using trial division by prime&lt;br /&gt;    numbers only. Returns a list of (possibly repeating) prime factors&lt;br /&gt;    """&lt;br /&gt;    t = clock()&lt;br /&gt;    ret =[]&lt;br /&gt;    nn = n&lt;br /&gt;    maxFactor = int(n**0.5)&lt;br /&gt;    primes = primeListSofE(maxFactor, verbose)&lt;br /&gt;    for p in primes :&lt;br /&gt;        while nn % p == 0 :&lt;br /&gt;            nn //= p&lt;br /&gt;            ret += [p]&lt;br /&gt;        if nn == 1 :&lt;br /&gt;            break&lt;br /&gt;    if nn != 1 :&lt;br /&gt;        ret += [nn]&lt;br /&gt;    t = clock() - t&lt;br /&gt;    if verbose :&lt;br /&gt;        print "Calculated factors of",n,"in",t,"sec."&lt;br /&gt;    return ret&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;While this function will be about as good as we can make it for numbers which are the product of two large prime factors, it will be terribly inefficient for most numbers. Consider, as an extreme example, that we are trying to factor 2&lt;sup&gt;55&lt;/sup&gt; ~ 3.6·10&lt;sup&gt;16&lt;/sup&gt;. We would first calculate all primes up to 1.9·10&lt;sup&gt;8&lt;/sup&gt;, a challenging feat in itself with our available tools, only to find out that we only needed the first of those primes, i.e. 2. Taking into account that 50% of all numbers are divisible by 2, 33% are divisible by 3, 20% are divisible by 5... it doesn't seem wise to disregard the potential time savings. What we can do to profit from this is to do the trial division checks at the same time as we determine the prime numbers, updating the largest prime to test on the fly. This has to be done in two stages, the first while we sieve up to n&lt;sup&gt;1/4&lt;/sup&gt;, the second while we search the rest of the sieve up to n&lt;sup&gt;1/2&lt;/sup&gt; searching for more primes. The following Franken-code has been written mostly by cut-and-paste from &lt;code&gt;primeListSofE&lt;/code&gt; and &lt;code&gt;factor&lt;/code&gt;, which hopefully hasn't affected its readability much:&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;from time import clock&lt;br /&gt;&lt;br /&gt;def factorAndSieve(n, verbose = False) :&lt;br /&gt;   """Returns all prime factors of n, using trial division while sieving&lt;br /&gt;   for primes. Returns a list of (possibly repeating) prime factors&lt;br /&gt;   """&lt;br /&gt;   t = clock()&lt;br /&gt;   ret =[]&lt;br /&gt;   nn = n&lt;br /&gt;   while nn % 2 == 0 : # remove 2's first, as 2 is not in sieve&lt;br /&gt;       nn //= 2&lt;br /&gt;       ret += [2]&lt;br /&gt;   maxFactor = int(nn**0.5)&lt;br /&gt;   maxI = (maxFactor-3) // 2&lt;br /&gt;   maxP = int(maxFactor**0.5)&lt;br /&gt;   sieve = [True for j in xrange(maxI+1)]&lt;br /&gt;   i = 0&lt;br /&gt;   for p in xrange(3, maxP+1,2) : # we then sieve as far as needed&lt;br /&gt;       if p &gt; maxP :&lt;br /&gt;           break&lt;br /&gt;       i = (p-3) // 2&lt;br /&gt;       if sieve[i] :&lt;br /&gt;           while nn % p == 0 :&lt;br /&gt;               nn //= p&lt;br /&gt;               ret += [p]&lt;br /&gt;               maxFactor = int(nn**0.5)&lt;br /&gt;               maxI = (maxFactor-3) // 2&lt;br /&gt;               maxP = int(maxFactor**0.5)&lt;br /&gt;           if nn == 1 :&lt;br /&gt;               break&lt;br /&gt;           else :&lt;br /&gt;               i2 = (p*p - 3) // 2&lt;br /&gt;               for k in xrange(i2, maxI+1, p) :&lt;br /&gt;                   sieve[k] = False&lt;br /&gt;   index = i&lt;br /&gt;   for i in xrange(index, maxI+1) : # and inspect the rest of the sieve&lt;br /&gt;       if i &gt; maxI :&lt;br /&gt;           break&lt;br /&gt;       if sieve[i] :&lt;br /&gt;           p = 2*i + 3&lt;br /&gt;           while nn % p == 0 :&lt;br /&gt;               nn //= p&lt;br /&gt;               ret += [p]&lt;br /&gt;               maxFactor = int(nn**0.5)&lt;br /&gt;               maxI = (maxFactor-3) // 2&lt;br /&gt;               maxP = int(maxFactor**0.5)&lt;br /&gt;           if nn == 1 :&lt;br /&gt;               break&lt;br /&gt;   if nn != 1 :&lt;br /&gt;       ret += [nn]&lt;br /&gt;   t = clock() - t&lt;br /&gt;   if verbose :&lt;br /&gt;       print "Calculated factors of",n,"in",t,"sec."&lt;br /&gt;       print "Stopped trial division at",2*i+3,"instead of",int(n**0.5)&lt;br /&gt;   return ret   &lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This new code will very often be much faster than the other one, but at times it will be just about as slow as in the other case, or even slower, since the mixing of both codes introduces some inefficiencies. The most extreme examples of such cases would be a prime number, or the square of a prime number on one side, and a power of 2 on the other one.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_47tBuP0my9o/Sd4W2kjwj3I/AAAAAAAAAIA/T1lCIBL2qtg/s1600-h/factorization1.png"&gt;&lt;img style="cursor: pointer; width: 400px; height: 247px;" src="http://3.bp.blogspot.com/_47tBuP0my9o/Sd4W2kjwj3I/AAAAAAAAAIA/T1lCIBL2qtg/s400/factorization1.png" alt="" id="BLOGGER_PHOTO_ID_5322716936380911474" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;The graph above plots times to calculate the factors of numbers between 10&lt;sup&gt;6&lt;/sup&gt; and 10&lt;sup&gt;6&lt;/sup&gt; + 100. Prime numbers in this interval stick out as the red dots among the blue ones: 10&lt;sup&gt;6&lt;/sup&gt; +3, +33, the &lt;a href="http://en.wikipedia.org/wiki/Twin_prime"&gt;twin primes&lt;/a&gt; +37 and +39, +81 and +99. And numbers with many small prime factors populate the bottom of the red cloud.&lt;br /&gt;&lt;br /&gt;If the above graph is not enough to convince you of the benefits of the second approach, maybe this timings for very large numbers will:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&gt;&gt;&gt; factor(10**15+37,True)&lt;br /&gt;Calculated primes to 31622776 in 6.760 sec.&lt;br /&gt;Calculated factors of 1000000000000037 in 8.466 sec.&lt;br /&gt;[1000000000000037L]&lt;br /&gt;&gt;&gt;&gt; factorAndSieve(10**15+37,True)&lt;br /&gt;Calculated factors of 1000000000000037 in 8.666 sec.&lt;br /&gt;Stopped trial division at 31622775 instead of 31622776&lt;br /&gt;[1000000000000037L]&lt;br /&gt;&lt;br /&gt;&gt;&gt;&gt; factor(2**55,True)&lt;br /&gt;Calculated primes to 189812531 in 42.811 sec.&lt;br /&gt;Calculated factors of 36028797018963968 in 43.261 sec.&lt;br /&gt;[2, ..., 2]&lt;br /&gt;&gt;&gt;&gt; factorAndSieve(2**55,True)&lt;br /&gt;Calculated factors of 36028797018963968 in 8.632e-05 sec.&lt;br /&gt;Stopped trial division at 3 instead of 189812531&lt;br /&gt;[2, ..., 2]&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/835341608950140555-2694194336765089829?l=numericalrecipes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://numericalrecipes.blogspot.com/feeds/2694194336765089829/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://numericalrecipes.blogspot.com/2009/04/naive-integer-factorization.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/2694194336765089829'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/2694194336765089829'/><link rel='alternate' type='text/html' href='http://numericalrecipes.blogspot.com/2009/04/naive-integer-factorization.html' title='Naive Integer Factorization'/><author><name>Jaime</name><uri>http://www.blogger.com/profile/02831887559711602902</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://1.bp.blogspot.com/_47tBuP0my9o/Sa6DmpICr3I/AAAAAAAAAGE/rGBLWTTlODU/S220/318462932_a2fef46344_m.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/_47tBuP0my9o/Sd4W2kjwj3I/AAAAAAAAAIA/T1lCIBL2qtg/s72-c/factorization1.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-835341608950140555.post-6984860435536970747</id><published>2009-03-24T02:30:00.000+01:00</published><updated>2009-03-24T02:42:20.034+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='sieving'/><category scheme='http://www.blogger.com/atom/ns#' term='primes'/><category scheme='http://www.blogger.com/atom/ns#' term='number theory'/><category scheme='http://www.blogger.com/atom/ns#' term='python'/><title type='text'>Prime Numbers 3. Wheel Factorization</title><content type='html'>In an &lt;a href="http://numericalrecipes.blogspot.com/2009/03/prime-numbers-2-sieving-of-erathostenes.html"&gt;earlier post&lt;/a&gt;, I described the &lt;a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes"&gt;sieve of Eratosthenes&lt;/a&gt;, a very fast algorithm to calculate all primes below a given limit, n. At least when programming it in python, speed is not an issue at all with this algorithm, because we start having memory problems much earlier, due to the fact that we need to keep in memory a list of size n...&lt;br /&gt;&lt;br /&gt;This is specially problematic with python, because although all we need is a list of booleans (is prime / is not prime), which could fit in a bit each, I'm afraid python assigns several bytes to each. How many of them is probably machine dependent, but I'm almost certain it is at least 4 of them. So it is very likely that we could improve memory usage by a factor of 32, maybe more, if we could get around this. There are &lt;a href="http://pypi.python.org/pypi/bitarray/"&gt;not-so-standard libraries&lt;/a&gt; that do just that, but I've sworn not to use them, and one day I may expose my failed attempts at using very long ints as bit arrays to the world, but python is definitely not the best language to mess around with low level optimizations, so I'm going to leave this line of thinking aside for the time being.&lt;br /&gt;&lt;br /&gt;I also presented a very naive optimization, which simply discards all even numbers, which we already know are not prime, and thus cuts in half the memory requirements. More formally, what was being done there was to &lt;a href="http://en.wikipedia.org/wiki/Partition_of_a_set"&gt;partition&lt;/a&gt; all numbers into two groups: those of the form 2·n, and those of the form 2·n+1, and then discard the former, since no prime of that form exists, and keep the latter only. This line of thinking is much more promising, as it leads to a very neat way of further reducing the memory required, known as &lt;a href="http://en.wikipedia.org/wiki/Wheel_factorization"&gt;wheel factorization&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;For some odd reason that escapes my shallow understanding, the standard description of this algorithm places much emphasis on setting all numbers in circles, and then eliminating what it calls spokes. I personally don't see any benefit of such a mental image, specially since the number are going to end up arranged in a rectangular array. So for the sake of clarity, I will not honor tradition, and spare you the circles and the spokes.&lt;br /&gt;&lt;br /&gt;We begin by choosing a first few prime numbers. Say the first three: 2, 3 and 5. We multiply them together to get M = 30. We are now going to partition the set of all numbers into M groups, of the form M·m + k&lt;sub&gt;i&lt;/sub&gt;, where the k&lt;sub&gt;i&lt;/sub&gt; are the numbers 1 through M, both inclusive. Most of these subsets happen to hold no prime number, and thus need not be considered at all. To find out which of them, remember that M is the product of several prime numbers, M = p&lt;sub&gt;1&lt;/sub&gt;·p&lt;sub&gt;2&lt;/sub&gt; ... p&lt;sub&gt;n&lt;/sub&gt;. Therefore, if k&lt;sub&gt;i&lt;/sub&gt; is a multiple of any of those prime numbers, i.e. k&lt;sub&gt;i&lt;/sub&gt; = p&lt;sub&gt;j&lt;/sub&gt;·k'&lt;sub&gt;i&lt;/sub&gt;, we can always extract the common factor p&lt;sub&gt;j&lt;/sub&gt; from both summands in M·m + k&lt;sub&gt;i&lt;/sub&gt;, which means that all numbers in that subset are composite. These subsets, which we discard, are very closely related to the spokes I was telling you about a while ago.&lt;br /&gt;&lt;br /&gt;If M = 30, of the 30 potential k&lt;sub&gt;i&lt;/sub&gt; we are left with just 8 (1, 7, 11, 13, 17, 19, 23 and 29), so we have cut memory required to about 27% of the straightforward implementation of the sieve of Eratosthenes. If we use the first 4 primes, we then have M = 210, and of the 210 potential k&lt;sub&gt;i&lt;/sub&gt; we only need to keep 48. This improves memory use, which now is roughly 23% of the original. But you can probably see a &lt;a href="http://en.wikipedia.org/wiki/Diminishing_returns"&gt;law of diminishing returns&lt;/a&gt; at wortk here: the improvement in memory use gets smaller and smaller with every prime you add to the calculation of M. You can find some more data regarding this at the end of &lt;a href="http://primes.utm.edu/glossary/page.php?sort=WheelFactorization"&gt;this link&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Of course we are still going to have to sieve each of our subsets, in much the same way we did with the sieve of Eratothenes. But sieving all multiples of a prime p when you have several subsets to consider is anything but trivial. Lets see how to tackle it...&lt;br /&gt;&lt;br /&gt;The question to answer is, what integer values of m fulfill the equation M·m + k&lt;sub&gt;i&lt;/sub&gt; = p·n? Using &lt;a href="http://en.wikipedia.org/wiki/Modular_arithmetic"&gt;modular arithmetic&lt;/a&gt;, this equation is equivalent to finding M·m = -k&lt;sub&gt;i&lt;/sub&gt; (mod p). This requires calculating M&lt;sup&gt;-1&lt;/sup&gt; (mod p), the &lt;a href="http://en.wikipedia.org/wiki/Modular_multiplicative_inverse"&gt;modular multiplicative inverse&lt;/a&gt; of M modulo p, a subject already treated in &lt;a href="http://numericalrecipes.blogspot.com/2009/03/modular-multiplicative-inverse.html"&gt;a previous post&lt;/a&gt;. Given that, we can simply write m&lt;sub&gt;i&lt;/sub&gt; = M&lt;sup&gt;-1&lt;/sup&gt;·(-k&lt;sub&gt;i&lt;/sub&gt;) (mod p), and therefore determine all multiples of p in the subset of k&lt;sub&gt;i&lt;/sub&gt; as m = p·j + m&lt;sub&gt;i&lt;/sub&gt;.&lt;br /&gt;&lt;br /&gt;Last, but not least, we want to start sieving at the smallest multiple of p in each subset that is larger than or equal to p&lt;sup&gt;2&lt;/sup&gt;, and so we want to increment m&lt;sub&gt;i&lt;/sub&gt; with p·j&lt;sub&gt;i&lt;/sub&gt;, where j&lt;sub&gt;i&lt;/sub&gt; &gt;= (p&lt;sup&gt;2&lt;/sup&gt;-k&lt;sub&gt;i&lt;/sub&gt;- M·m&lt;sub&gt;i&lt;/sub&gt;) / (m·p).&lt;br /&gt;&lt;br /&gt;Lets try to put all this ideas together in a python script. To make it work, you will need the &lt;code&gt;primeListSofE&lt;/code&gt; function from &lt;a href="http://numericalrecipes.blogspot.com/2009/03/prime-numbers-2-sieving-of-erathostenes.html"&gt;this post&lt;/a&gt;, as well as the &lt;code&gt;extEuclideanAlg&lt;/code&gt; and &lt;code&gt;modInvEuclid&lt;/code&gt; ones from &lt;a href="http://numericalrecipes.blogspot.com/2009/03/modular-multiplicative-inverse.html"&gt;this other post&lt;/a&gt;...&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;def primeListWF(n, m, verbose = True) :&lt;br /&gt;    """Returns a list of prime numbers smaller than or equal to n,&lt;br /&gt;    using wheel factorization, with a wheel size of the product of&lt;br /&gt;    all primes smaller than or equal to m&lt;br /&gt;    """&lt;br /&gt;    t = time()&lt;br /&gt;    # We use the standard sieve of Eratosthenes first...&lt;br /&gt;    primes = primeListSofE(m)&lt;br /&gt;    M = 1&lt;br /&gt;    for p in primes :&lt;br /&gt;        M *= p&lt;br /&gt;    if verbose :&lt;br /&gt;        print "Size of factorization wheel is",M&lt;br /&gt;    # We now sieve out all multiples of these primes,including&lt;br /&gt;    # the primes themselves, to get the k[i]&lt;br /&gt;    sieve = [True] * M&lt;br /&gt;    for p in primes :&lt;br /&gt;        sieve[p-1] = False&lt;br /&gt;        for j in xrange(p*p,M+1,p) :&lt;br /&gt;            sieve[j-1] = False&lt;br /&gt;    k = [j+1 for j in range(M) if sieve[j]]&lt;br /&gt;    if verbose :&lt;br /&gt;        print "Memory use is only",len(k),"/",M,"=",len(k)/M&lt;br /&gt;    N = n&lt;br /&gt;    if N %M :&lt;br /&gt;        N += M&lt;br /&gt;    N //= M&lt;br /&gt;    maxP = int(sqrt(M*N))&lt;br /&gt;    if verbose:&lt;br /&gt;        print "Primes will be calculated up to",M*N,"not",n&lt;br /&gt;&lt;br /&gt;    sieve = [[True]*N for j in range(len(k))]&lt;br /&gt;    sieve[0][0] = False # Take care of the non primality of 1&lt;br /&gt;    for row in range(N) :&lt;br /&gt;        baseVal = M * row&lt;br /&gt;        for subset in range(len(k)) :&lt;br /&gt;            if sieve[subset][row] :&lt;br /&gt;                p = baseVal + k[subset]&lt;br /&gt;                primes += [p]&lt;br /&gt;                if p &gt; maxP :&lt;br /&gt;                    continue&lt;br /&gt;                # Sieve all multiples of p...&lt;br /&gt;                invMp = modInvEuclid(M,p)&lt;br /&gt;                for i in range(len(k)) :&lt;br /&gt;                    mi = invMp * (-k[i] % p)&lt;br /&gt;                    mi %= p&lt;br /&gt;                    # ...starting at p**2&lt;br /&gt;                    ji = (p*p - k[i] - M*mi)&lt;br /&gt;                    if ji % (M*p) :&lt;br /&gt;                        ji += M*p&lt;br /&gt;                    ji //= M*p&lt;br /&gt;                    mi+= ji*p&lt;br /&gt;&lt;br /&gt;                    for r in range(mi,N,p) :&lt;br /&gt;                        sieve[j][r] = False&lt;br /&gt;    if verbose :&lt;br /&gt;        print "Calculated primes to",n,"in",time()-t,"sec."&lt;br /&gt;        &lt;br /&gt;    return primes&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;You can play around with this algorithm and look at the time required. It probably depends on the value of n, but there seems to be a sweet spot for speed somewhere around m = 7 (and thus M = 210) or m = 11 (M = 2310). This being a general purpose wheel factorization algorithm, it has speeds that are faster than the unoptimized sieve of Eratosthenes code, but it cannot beat the optimized code, which in fact is a particular case of wheel factorization, for m = M = 2.&lt;br /&gt;&lt;br /&gt;On the other hand, using m = 7 I have managed to compute all primes up to 10&lt;sup&gt;8&lt;/sup&gt;, a feat unreachable for the previous code, at least without finding a workaround the &lt;code&gt;MemoryError&lt;/code&gt; they produce. 10&lt;sup&gt;9&lt;/sup&gt; is still out of reach, though...&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/835341608950140555-6984860435536970747?l=numericalrecipes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://numericalrecipes.blogspot.com/feeds/6984860435536970747/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://numericalrecipes.blogspot.com/2009/03/prime-numbers-3-wheel-factorization.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/6984860435536970747'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/6984860435536970747'/><link rel='alternate' type='text/html' href='http://numericalrecipes.blogspot.com/2009/03/prime-numbers-3-wheel-factorization.html' title='Prime Numbers 3. Wheel Factorization'/><author><name>Jaime</name><uri>http://www.blogger.com/profile/02831887559711602902</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://1.bp.blogspot.com/_47tBuP0my9o/Sa6DmpICr3I/AAAAAAAAAGE/rGBLWTTlODU/S220/318462932_a2fef46344_m.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-835341608950140555.post-4548605990358051563</id><published>2009-03-20T14:01:00.010+01:00</published><updated>2009-03-22T21:52:13.829+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='primes'/><category scheme='http://www.blogger.com/atom/ns#' term='number theory'/><category scheme='http://www.blogger.com/atom/ns#' term='python'/><category scheme='http://www.blogger.com/atom/ns#' term='modular arithmetic'/><title type='text'>Modular Multiplicative Inverse</title><content type='html'>Now that we are all proficient with &lt;a href="http://en.wikipedia.org/wiki/Modular_exponentiation"&gt;modular exponentiation&lt;/a&gt; thanks to my &lt;a href="http://numericalrecipes.blogspot.com/2009/03/modular-exponentiation.html"&gt;previous post&lt;/a&gt;, it is time to tackle a more complicated issue, still in the realm of &lt;a href="http://en.wikipedia.org/wiki/Modular_arithmetic"&gt;modular arithmetic&lt;/a&gt;.&lt;br /&gt;While addition, subtraction and multiplication are "compatible with the congruence relation" introduced by modular arithmetic, the same doesn't happen with division. This means that solving a simple equation such as a·x = 1 (mod m) is anything but trivial. In fact, determining x = a&lt;sup&gt;-1&lt;/sup&gt; (mod m) that fulfills that equation is the whole object of this post...&lt;br /&gt;&lt;br /&gt;There is, as always, the brute force approach, which I always like to visit first, so that I can later congratulate myself on how much the efficiency has improved with my deep insight. In this particular case, brute force means trying every number between 1 and m-1, and see if the m-modulo of its product with a is 1. :&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;def modInv1(a,m) :&lt;br /&gt;  """Computes the modular multiplicative inverse of a modulo m,&lt;br /&gt;  using brute force&lt;br /&gt;  """&lt;br /&gt;  a %= m&lt;br /&gt;  for x in range(1,m) :&lt;br /&gt;      if a*x%m == 1 :&lt;br /&gt;          return x&lt;br /&gt;  return None&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Do notice that the possibility of no multiplicative inverse existing is contemplated in the code. This will actually be the case if a and m have any common factors, i.e. if they are not &lt;a href="http://en.wikipedia.org/wiki/Coprime"&gt;coprime&lt;/a&gt;. So the previous code could serve as a moron's approach to determining if two numbers are relatively prime. Not that I recommend it, though, as it should be clear that the code I have just produced will be very inefficient for large values of m.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;The Extended Euclidean Algorithm&lt;/span&gt;&lt;br /&gt;As stated, we are after a number x that fulfills a·x = 1 (mod m). This can of course be written as well as a·x = 1 + m·y, which rearranges neatly into a·x - m·y = 1. Since x and y need not be positive, we can write it as well in the standard form, a·x + m·y = 1. If a and m are coprime, this is a particular instance of a·x + b·y = gcd(a,b), where gcd(a,b) is the &lt;a href="http://en.wikipedia.org/wiki/Greatest_common_divisor"&gt;greatest common divisor&lt;/a&gt; of a and b. This equatiin is known as &lt;a href="http://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity"&gt;Bézout's identity&lt;/a&gt;, and can be efficiently solved using the &lt;a href="http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm"&gt;extended Euclidean algorithm&lt;/a&gt;. To find a solution to our particular equation, this algorithm would proceed as follows:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;Rewrite the equation as a&lt;sub&gt;n&lt;/sub&gt;·x&lt;sub&gt;n&lt;/sub&gt; + m&lt;sub&gt;n&lt;/sub&gt;·y&lt;sub&gt;n&lt;/sub&gt; = 1, starting with n = 0 &lt;/li&gt;&lt;li&gt;Compute the quotient, q&lt;sub&gt;n&lt;/sub&gt;, and the remainder, r&lt;sub&gt;n&lt;/sub&gt;, of a&lt;sub&gt;n&lt;/sub&gt; divided by m&lt;sub&gt;n&lt;/sub&gt;, and rewrite the original equation as (m&lt;sub&gt;n&lt;/sub&gt;·q&lt;sub&gt;n&lt;/sub&gt; + r&lt;sub&gt;n&lt;/sub&gt;)·x&lt;sub&gt;n&lt;/sub&gt; + m&lt;sub&gt;n&lt;/sub&gt;·y&lt;sub&gt;n&lt;/sub&gt; =1&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Rearrange the terms in the equation to get m&lt;sub&gt;n&lt;/sub&gt;·(q&lt;sub&gt;n&lt;/sub&gt;·x&lt;sub&gt;n&lt;/sub&gt;+y&lt;sub&gt;n&lt;/sub&gt;) + r&lt;sub&gt;n&lt;/sub&gt;·x&lt;sub&gt;n&lt;/sub&gt; = 1&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Do the changes of variables&lt;br /&gt;&lt;ul&gt;&lt;li&gt;x&lt;sub&gt;n+1&lt;/sub&gt; = q&lt;sub&gt;n&lt;/sub&gt;·x&lt;sub&gt;n&lt;/sub&gt;+y&lt;sub&gt;n&lt;/sub&gt;,&lt;br /&gt;&lt;/li&gt;&lt;li&gt;y&lt;sub&gt;n+1&lt;/sub&gt; = x&lt;sub&gt;n&lt;/sub&gt;,&lt;br /&gt;&lt;/li&gt;&lt;li&gt;a&lt;sub&gt;n+1&lt;/sub&gt; = m&lt;sub&gt;n,&lt;/sub&gt; and&lt;br /&gt;&lt;/li&gt;&lt;li&gt;m&lt;sub&gt;n+1&lt;/sub&gt; = r&lt;sub&gt;n&lt;/sub&gt;&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;Repeat the process, until a&lt;sub&gt;n&lt;/sub&gt; = 1, and m&lt;sub&gt;n&lt;/sub&gt; = 0.&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Such equations has the trivial solution x&lt;sub&gt;n&lt;/sub&gt; = 1, y&lt;sub&gt;n&lt;/sub&gt; = 0.&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Work your way back to x&lt;sub&gt;0&lt;/sub&gt; and y&lt;sub&gt;0&lt;/sub&gt;, noting that&lt;br /&gt;&lt;ul&gt;&lt;li&gt;x&lt;sub&gt;n-1&lt;/sub&gt; = y&lt;sub&gt;n&lt;/sub&gt;,&lt;br /&gt;&lt;/li&gt;&lt;li&gt;y&lt;sub&gt;n-1&lt;/sub&gt; = x&lt;sub&gt;n&lt;/sub&gt; - q&lt;sub&gt;n-1&lt;/sub&gt;·y&lt;sub&gt;n&lt;/sub&gt;&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;x&lt;sub&gt;0&lt;/sub&gt; is the number we are after.&lt;br /&gt;&lt;/li&gt;&lt;/ol&gt;There is a certain component of faith in believing that, eventually, a&lt;sub&gt;n&lt;/sub&gt; = 1 and m&lt;sub&gt;n&lt;/sub&gt; = 0. It is in fact not always the case, as if a and m are not coprime, then the values we will arrive at are m&lt;sub&gt;n&lt;/sub&gt; = 0, but a&lt;sub&gt;n&lt;/sub&gt; = gcd(a,m). As a matter of fact, the gcd is normally computed using the &lt;a href="http://en.wikipedia.org/wiki/Euclidean_algorithm"&gt;Euclidean algorithm&lt;/a&gt;, dropping the adjective extended, which basically does the same as above, but without the back-tracking of the x&lt;sub&gt;n&lt;/sub&gt;'s and the y&lt;sub&gt;n&lt;/sub&gt;'s. With all of this in mind, we can write two functions, one calling the other, as follows:&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;def extEuclideanAlg(a, b) :&lt;br /&gt;  """Computes a solution  to a x + b y = gcd(a,b), as well as gcd(a,b)&lt;br /&gt;  """&lt;br /&gt;  if b == 0 :&lt;br /&gt;      return 1,0,a&lt;br /&gt;  else :&lt;br /&gt;      x, y, gcd = extEuclideanAlg(b, a % b)&lt;br /&gt;      return y, x - y * (a // b),gcd&lt;br /&gt;&lt;br /&gt;def modInvEuclid(a,m) :&lt;br /&gt;  """Computes the modular multiplicative inverse of a modulo m,&lt;br /&gt;  using the extended Euclidean algorithm&lt;br /&gt;  """&lt;br /&gt;  x,y,gcd = extEuclideanAlg(a,m)&lt;br /&gt;  if gcd == 1 :&lt;br /&gt;      return x % m&lt;br /&gt;  else :&lt;br /&gt;      return None&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The gains in speed are tremendous with this new approach. Again, write your own testing function as an exercise, but mine spits out the following results...&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&gt;&gt;&gt; testModInv(1234,5,10000)&lt;br /&gt;Got 4 using method 1 in 0.0160000324249 sec.&lt;br /&gt;Got 4 using Euclidean algorithm in 0.0309998989105 sec.&lt;br /&gt;&lt;br /&gt;&gt;&gt;&gt; testModInv(1234,56789,10000)&lt;br /&gt;Got 31800 using method 1 in 59.4000101089 sec.&lt;br /&gt;Got 31800 using Euclidean algorithm in 0.047000169754 sec.&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;So while brute force is good enough, or even the best choice, for very small values of m, as soon as it grows, the benefits of the more elaborate algorithm are all too obvious. According to wikipedia, the algorithm we have coded has complexity O(log(m)&lt;sup&gt;2&lt;/sup&gt;), i.e. time required to compute the modular multiplicative inverse is proportional to log(m)&lt;sup&gt;2&lt;/sup&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/835341608950140555-4548605990358051563?l=numericalrecipes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://numericalrecipes.blogspot.com/feeds/4548605990358051563/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://numericalrecipes.blogspot.com/2009/03/modular-multiplicative-inverse.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/4548605990358051563'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/4548605990358051563'/><link rel='alternate' type='text/html' href='http://numericalrecipes.blogspot.com/2009/03/modular-multiplicative-inverse.html' title='Modular Multiplicative Inverse'/><author><name>Jaime</name><uri>http://www.blogger.com/profile/02831887559711602902</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://1.bp.blogspot.com/_47tBuP0my9o/Sa6DmpICr3I/AAAAAAAAAGE/rGBLWTTlODU/S220/318462932_a2fef46344_m.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-835341608950140555.post-4100717355061456049</id><published>2009-03-20T12:08:00.013+01:00</published><updated>2009-03-25T18:22:08.757+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='number theory'/><category scheme='http://www.blogger.com/atom/ns#' term='python'/><category scheme='http://www.blogger.com/atom/ns#' term='modular arithmetic'/><title type='text'>Modular Exponentiation</title><content type='html'>I have a post cooking on &lt;a href="http://en.wikipedia.org/wiki/Wheel_factorization"&gt;wheel factorization&lt;/a&gt;, yet another sieving algorithm  for the computation of all primes below a given number n. It turns out that while implementing it, one comes across a number of not so obvious preliminary questions. It is a rule of this blog not to resort to any non standard library, and I feel it would be breaking the spirit of that rule to post code which hasn't been thoroughly explained in advance. So in order not to make that soon-to-be post on prime numbers longer than anyone could bear, I find myself in need of covering a couple of preliminaries, and so here comes this thrilling post on &lt;a href="http://en.wikipedia.org/wiki/Modular_exponentiation"&gt;modular exponentiation&lt;/a&gt;...&lt;br /&gt;&lt;br /&gt;What we are after is determining a&lt;sup&gt;b&lt;/sup&gt; (mod m), or to put it in plain English, the remainder of a to the power of b, divided by m. Doesn't seem much, does it? We could just go ahead and write:&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;def modExp1(a, b, m) :&lt;br /&gt;   """Computes a to the power b, modulo m, directly&lt;br /&gt;   """&lt;br /&gt;   return a**b % m&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The problems begin if a and b are both big. Python's integers don't overflow, and we all love it for it, but the memory juggling it has to do to accommodate a huge number in memory does come at a speed cost. Specially if m is small, it definitely seems a little overkill to keep a zillion digit number in memory, given that the answer will be smaller than m...&lt;br /&gt;&lt;br /&gt;We can, and will, use &lt;a href="http://en.wikipedia.org/wiki/Modular_arithmetic"&gt;modular arithmetic&lt;/a&gt; to our advantage. See, wikipedia says that "the congruence relation (introduced by modular arithmetic) on the integers is compatible with the multiplication operation of the ring of integers," and if it's on the internet it has to be true, right? Translated to plain English, the idea is that if we want to take the product of two numbers, a and b, modulo m, we can first multiply them, and then take the m-modulo of the result, or we can take the m-modulo of a and/or b, prior to multiplication, and the m-modulo of the result will still be the right answer. So the least a conscious programmer should do is to rewrite the previous function as:&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;def modExp2(a, b, m) :&lt;br /&gt;    """Computes a to the power b, modulo m, a little less directly&lt;br /&gt;    """&lt;br /&gt;    return (a%m)**b % m&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Of course, if b is large enough, you may still find yourself in the realm of zillion digit numbers, which is a place we don't really want to go. It turns out then that it may be a good option to remember that exponentiation is just repeated multiplication. If we multiply a by itself b times, and take the m-modulo of the result, the larger number we will ever have in memory will be m&lt;sup&gt;2&lt;/sup&gt;. It doesn't really seem right to put a loop of b iterations into the code, since what we are worried about are large b's, but lets do it anyway:&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;def modExp3(a, b, m) :&lt;br /&gt;    """Computes a to the power b, modulo m, by iterative multiplication&lt;br /&gt;    """&lt;br /&gt;    ret = 1&lt;br /&gt;    a %= m&lt;br /&gt;    while b :&lt;br /&gt;        ret *= a&lt;br /&gt;        ret %= m&lt;br /&gt;        b -= 1&lt;br /&gt;    return ret&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The only reason why this last function deserves a place here, is because it helps introduce the really cool algorithm that this whole post really is about, &lt;a href="http://en.wikipedia.org/wiki/Binary_exponentiation"&gt;binary exponentiation&lt;/a&gt;. In &lt;a href="http://www.johndcook.com/blog/2008/12/10/fast-exponentiation/"&gt;John D. Cook's blog&lt;/a&gt; there is a great explanation on how it could be implemented iteratively, based on the binary representation of the exponent, but I'll go for a recursive version, which is essentially the same, but which I find easier for my brain's wiring...&lt;br /&gt;&lt;br /&gt;So what we are about to do is, when asked to compute a&lt;sup&gt;b&lt;/sup&gt;, check if b is even, in which case we will compute it as the square of a&lt;sup&gt;b/2&lt;/sup&gt;. If b is odd, we will compute it as a a&lt;sup&gt;b-1&lt;/sup&gt;. If b is 0, we will of course return 1. If we also throw in all the modulo m stuff I have been discussing previously, we finally arrive at THE function to do modular exponentiation:&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;def modExp(a, b, m) :&lt;br /&gt;    """Computes a to the power b, modulo m, using binary exponentiation&lt;br /&gt;    """&lt;br /&gt;    a %= m&lt;br /&gt;    ret = None&lt;br /&gt;    &lt;br /&gt;    if b == 0 :&lt;br /&gt;        ret = 1&lt;br /&gt;    elif b%2 :&lt;br /&gt;        ret = a * modExp(a,b-1,m)&lt;br /&gt;    else :&lt;br /&gt;        ret = modExp(a,b//2,m)&lt;br /&gt;        ret *= ret&lt;br /&gt;        &lt;br /&gt;    return ret%m&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now that we have all four versions of the same function written, we can do a little testing, I will leave writing the testing code as an exercise for the reader (I've been wanting to say this since my first year of university...), but when computing 1234 to the power 5678, modulo 90, a 1000 times with each function, these is the performance I get:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&gt;&gt;&gt; testModExp(1234,5678,90,1000)&lt;br /&gt;Got 46 using method 1 in 3.73399996758 sec.&lt;br /&gt;Got 46 using method 2 in 0.546999931335 sec.&lt;br /&gt;Got 46 using method 3 in 1.25 sec.&lt;br /&gt;Got 46 using THE method in 0.0150001049042 sec.&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;Results which really don't require much commenting...&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;EDIT:&lt;/span&gt; There is some very interesting information in the comments: python comes with a built-in &lt;code&gt;pow&lt;code&gt; function, which can take two or three arguments, the third being, precisely, the modulo. It probably implements an algorithm similar to what has been presented, but is more than an order of magnitude faster.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/835341608950140555-4100717355061456049?l=numericalrecipes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://numericalrecipes.blogspot.com/feeds/4100717355061456049/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://numericalrecipes.blogspot.com/2009/03/modular-exponentiation.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/4100717355061456049'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/4100717355061456049'/><link rel='alternate' type='text/html' href='http://numericalrecipes.blogspot.com/2009/03/modular-exponentiation.html' title='Modular Exponentiation'/><author><name>Jaime</name><uri>http://www.blogger.com/profile/02831887559711602902</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://1.bp.blogspot.com/_47tBuP0my9o/Sa6DmpICr3I/AAAAAAAAAGE/rGBLWTTlODU/S220/318462932_a2fef46344_m.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-835341608950140555.post-3611595397854470385</id><published>2009-03-16T00:12:00.016+01:00</published><updated>2009-03-21T08:43:29.743+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='sieving'/><category scheme='http://www.blogger.com/atom/ns#' term='primes'/><category scheme='http://www.blogger.com/atom/ns#' term='number theory'/><category scheme='http://www.blogger.com/atom/ns#' term='python'/><title type='text'>Prime Numbers 2. The Sieve of Erathostenes</title><content type='html'>The problem with the algorithms described in the &lt;a href="http://numericalrecipes.blogspot.com/2009/03/prime-numbers_04.html"&gt;previous post&lt;/a&gt; lies on the very large amount of redundant testing that goes on. Because once we have checked the primality of a certain number p, we know that 2p, 3p, 4p, ..., np are composites. So what is the point of checking those numbers at all? When you follow this line of thinking to the very end, it turns out you don't have to do any trial division at all! The resulting algorithm is attributed to &lt;a href="http://en.wikipedia.org/wiki/Eratosthenes"&gt;Erathostenes&lt;/a&gt;, and it employs a technique, known as &lt;a href="http://en.wikipedia.org/wiki/Sieve_theory"&gt;sieving&lt;/a&gt;, which may come in handy in many other problems. But enough for a presentation, lets get going with the &lt;a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes"&gt;Sieve of Erathostenes&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;All the information we need to begin with, is that 2 is the first prime. This means, following the previous approach, that no other even number can be prime. To keep track of this information, we begin by writing a list of all the numbers between 2 and the desired limit, say N:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_47tBuP0my9o/ScEwu3RTIyI/AAAAAAAAAHI/zBdrGZgQ0Z0/s1600-h/sieving1.png"&gt;&lt;img style="cursor: pointer; width: 400px; height: 19px;" src="http://2.bp.blogspot.com/_47tBuP0my9o/ScEwu3RTIyI/AAAAAAAAAHI/zBdrGZgQ0Z0/s400/sieving1.png" alt="" id="BLOGGER_PHOTO_ID_5314582616942519074" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;We now draw a circle around 2, because it is prime, and then strike out all even numbers, i.e. all multiples of 2:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/_47tBuP0my9o/ScEx_oQWp2I/AAAAAAAAAHg/WUq50_6K0aM/s1600-h/sieving2.png"&gt;&lt;img style="cursor: pointer; width: 400px; height: 34px;" src="http://4.bp.blogspot.com/_47tBuP0my9o/ScEx_oQWp2I/AAAAAAAAAHg/WUq50_6K0aM/s400/sieving2.png" alt="" id="BLOGGER_PHOTO_ID_5314584004481427298" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Now, there is a good and a bad way to strike out all multiples of a number from a list. The wrong way is to do trial division to find out if it is a multiple. The right way is to use the fact that two consecutive multiples of a number differ by that exact number. Writing it out in python, you can check the tremendous gain for yourself:&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;from time import time&lt;br /&gt;&lt;br /&gt;def strikeOut(mul, n) :&lt;br /&gt;&lt;br /&gt;# note that list index i corresponds to number i+2&lt;br /&gt;sieve = [True for j in xrange(2,n+1)]&lt;br /&gt;&lt;br /&gt;# The bad way to sieve&lt;br /&gt;t = time()&lt;br /&gt;for j in xrange(2,n+1) :&lt;br /&gt;   if j % mul == 0 :&lt;br /&gt;       sieve[j-2] = False&lt;br /&gt;t = time() - t&lt;br /&gt;print "Sieved (bad!!!) all multiples of",mul,"below",n,"in",t,"sec."&lt;br /&gt;&lt;br /&gt;sieve = [True for j in xrange(2,n+1)]&lt;br /&gt;&lt;br /&gt;# The good way to sieve&lt;br /&gt;t = time()&lt;br /&gt;for j in xrange(mul,n+1,mul) :&lt;br /&gt;       sieve[j-2] = False&lt;br /&gt;t = time() - t&lt;br /&gt;print "Sieved (good!!!) all multiples of",mul,"below",n,"in",t,"sec."&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;No, I'm not taking you, dear reader, for an idiot: you can find sieving algorithms on fist pages of google searches that do sieving this very wrong way...&lt;br /&gt;&lt;br /&gt;But lets get back to primes. We had our list, with 2 circled and all its multiples crossed out. The first unmarked number we come across is 3. Just a coincidence that 3 is a prime number? Not really: it it is unmarked because it is not a multiple of any smaller number. Or to put it another way: it is only divisible by 1 and itself, which is hte very definition of prime... So we circle 3 and cross out all its multiples:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_47tBuP0my9o/ScEx0khjENI/AAAAAAAAAHY/ib6-anRapmA/s1600-h/sieving3.png"&gt;&lt;img style="cursor: pointer; width: 400px; height: 39px;" src="http://1.bp.blogspot.com/_47tBuP0my9o/ScEx0khjENI/AAAAAAAAAHY/ib6-anRapmA/s400/sieving3.png" alt="" id="BLOGGER_PHOTO_ID_5314583814501241042" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;I've underlined the multiples of three that where already crossed out. The first number which gets crossed out for the first time is 9. Will it be just a coincidence that 9 = 3&lt;sup&gt;2&lt;/sup&gt;? Of course not! We have already crossed out all multiples of numbers smaller than 3, and 3&lt;sup&gt;2&lt;/sup&gt; is the first multiple of 3 which is not a multiple of any smaller number.&lt;br /&gt;&lt;br /&gt;So we keep going down our list, and find 5 to be the next unmarked number in the list, which of course is prime, so we circle it, and then cross out all of its multiples. But as we saw before, rather than starting at 10, and crossing out the already crossed out 10, 15 and 20, we proceed directly to 5&lt;sup&gt;2&lt;/sup&gt;, that is 25.&lt;br /&gt;&lt;br /&gt;This goes on until we've searched the whole list, circling numbers and crossing out its multiples. But since we start crossing out at the square of the new found prime, we only need to do the crossing out for primes smaller than the square root of N: once we get there, any uncrossed number up to N will be prime. This is what the beginning of our list will look like once we are through:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/_47tBuP0my9o/ScE1UJG8qGI/AAAAAAAAAHo/PcMD2_SQ2Yc/s1600-h/sieving4.png"&gt;&lt;img style="cursor: pointer; width: 400px; height: 41px;" src="http://4.bp.blogspot.com/_47tBuP0my9o/ScE1UJG8qGI/AAAAAAAAAHo/PcMD2_SQ2Yc/s400/sieving4.png" alt="" id="BLOGGER_PHOTO_ID_5314587655432611938" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;So lets try and write our very own sieve of Erathostenes in python, with all this square and square root tricks pointed out above...&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;from time import time&lt;br /&gt;from math import sqrt&lt;br /&gt;&lt;br /&gt;def primeListSofE(n, verbose = True) :&lt;br /&gt; t = time()&lt;br /&gt; sieve = [True for j in xrange(2,n+1)]&lt;br /&gt; for j in xrange(2,int(sqrt(n))+1) :&lt;br /&gt;     i = j-2&lt;br /&gt;     if sieve[i]:&lt;br /&gt;         for k in range(j*j,n+1,j) :&lt;br /&gt;             sieve[k-2] = False&lt;br /&gt;&lt;br /&gt; ret = [j for j in xrange(2,n+1) if sieve[j-2]]&lt;br /&gt;&lt;br /&gt; if verbose :&lt;br /&gt;     print "Calculated primes to",n,"in",time()-t,"sec."&lt;br /&gt;&lt;br /&gt; return ret&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Play around with it and once more feel the thrill of speed. On my computer it does all primes below 1,000,000 almost 5 times faster than the best trial division approach from the previous post. But the real beauty is in how the time now scales with n, because you can no longer find a suitable fit of the form n&lt;sup&gt;q&lt;/sup&gt;. We haven't simply reduced the size of the exponent, but are treading uncharted territory, as it turns out that the time required to calculate all primes below using this sieve requires (n.log(n))(log(log(n))) time. Actually, for the first 10&lt;sup&gt;10&lt;/sup&gt; numbers, this is basically indistinguishable from linear time, i.e proportional to n.&lt;br /&gt;&lt;br /&gt;This speed does come at a memory cost, though: you need to store an array of size n. And while the algorithm could produce all primes below 10&lt;sup&gt;10&lt;/sup&gt; in just a few minutes, the program will very likely crash giving an out of memory error. Some memory saving can be done by not storing even numbers at all. Without boring you with the details, below is the python function I use to compute primes at work, which does 10&lt;sup&gt;7&lt;/sup&gt; almost three times faster than the previous one, and uses half the memory, but still crashes when asked for all primes below 10&lt;sup&gt;9&lt;/sup&gt;...&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;from time import time&lt;br /&gt;from math import sqrt&lt;br /&gt;&lt;br /&gt;def primeListSofE(n, verbose = False) :&lt;br /&gt;  """Returns a list of prime numbers smaller than or equal to n,&lt;br /&gt;  using an optimized sieve of Erathostenes algorithm.&lt;br /&gt;  """&lt;br /&gt;  t = time()&lt;br /&gt;  maxI = (n-3) // 2&lt;br /&gt;  maxP = int(sqrt(n))&lt;br /&gt;  sieve = [True for j in xrange(maxI+1)]&lt;br /&gt;  for p in xrange(3,maxP+1,2) :&lt;br /&gt;      i = (p-3) // 2&lt;br /&gt;      if sieve[i] :&lt;br /&gt;          i2 = (p*p-3) // 2&lt;br /&gt;          for k in xrange(i2,maxI+1,p) :&lt;br /&gt;              sieve[k] = False&lt;br /&gt;  ret = [2]+[2*j+3 for j in xrange(len(sieve)) if sieve[j]]&lt;br /&gt;  if verbose :&lt;br /&gt;      print "Calculated primes to",n,"in",time()-t,"sec."&lt;br /&gt;  return ret&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;There are slightly faster ways of sieving, and we could &lt;a href="http://en.wikipedia.org/wiki/Memoization"&gt;memoize&lt;/a&gt; precalculated primes, to speed up repeated calls to the function. But this is probably enough for today's post...&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/835341608950140555-3611595397854470385?l=numericalrecipes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://numericalrecipes.blogspot.com/feeds/3611595397854470385/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://numericalrecipes.blogspot.com/2009/03/prime-numbers-2-sieving-of-erathostenes.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/3611595397854470385'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/3611595397854470385'/><link rel='alternate' type='text/html' href='http://numericalrecipes.blogspot.com/2009/03/prime-numbers-2-sieving-of-erathostenes.html' title='Prime Numbers 2. The Sieve of Erathostenes'/><author><name>Jaime</name><uri>http://www.blogger.com/profile/02831887559711602902</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://1.bp.blogspot.com/_47tBuP0my9o/Sa6DmpICr3I/AAAAAAAAAGE/rGBLWTTlODU/S220/318462932_a2fef46344_m.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_47tBuP0my9o/ScEwu3RTIyI/AAAAAAAAAHI/zBdrGZgQ0Z0/s72-c/sieving1.png' height='72' width='72'/><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-835341608950140555.post-7631306534593538485</id><published>2009-03-05T14:50:00.004+01:00</published><updated>2009-03-20T17:56:53.860+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='primes'/><category scheme='http://www.blogger.com/atom/ns#' term='number theory'/><category scheme='http://www.blogger.com/atom/ns#' term='python'/><title type='text'>Prime Numbers 1. The Wrong Way</title><content type='html'>A &lt;a href="http://en.wikipedia.org/wiki/Prime_number"&gt;prime number&lt;/a&gt; is a natural number larger than 1 which is only divisible by 1 and itself. Simple, isn't it? &lt;a href="http://en.wikipedia.org/wiki/Prime_number"&gt;Euclid&lt;/a&gt; already &lt;a href="http://www-users.cs.york.ac.uk/%7Esusan/cyc/p/primeprf.htm"&gt;proved&lt;/a&gt; quite a while ago that there are infinitely many of them, so lets try and write a function that returns all primes below a given number, using the most straightforward approach. Whta would that be? Well, there is nothing less sophisticated than try and divide each number by every integer larger than 1 and smaller than the number itself, and if we never get a zero remainder then the number is prime. Putting it in python:&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;from time import time&lt;br /&gt;&lt;br /&gt;def primeList1(n, verbose = True) :&lt;br /&gt;t = time()&lt;br /&gt;ret = []&lt;br /&gt;for j in range(2,n+1) :&lt;br /&gt;    jIsPrime = True&lt;br /&gt;    for k in range(2,j) :&lt;br /&gt;        if j % k == 0 :&lt;br /&gt;            jIsPrime = False&lt;br /&gt;            break&lt;br /&gt;    if jIsPrime :&lt;br /&gt;        ret += [j]&lt;br /&gt;if verbose :&lt;br /&gt;    print "Calculated primes to",n,"in",time()-t,"sec."&lt;br /&gt;&lt;br /&gt;return ret&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Do notice the feeble attempt at code optimization, with the &lt;code&gt;break&lt;/code&gt; statement that ends the loop as soon as a divisor is found... If you try it out, it will work fine. Use it to calculate all prime numbers below 1,000, and it will probably give you an instant answer. 10,000 delays a second or two, nothing too worrying. If you try it with 100,000, you'll have time to take your coffee break before it finishes, and adding any more zeroes will require leaving your script running overnight... Not too surprising really, since to determine that, for example, 9973 is indeed a prime number, our program is having to do trial division by every number between 2 and 9972, both inclusive. All in all, the time required grows with n&lt;sup&gt;2&lt;/sup&gt;.&lt;br /&gt;&lt;br /&gt;There are several very simple improvements that can speed things up dramatically, and which require a little, but just a little, mathematical insight...&lt;br /&gt;&lt;br /&gt;First, we don't need to test every number between 2 and 9972 to determine that 9973 is prime; we can stop after the largest integer smaller than the square-root of 9973, i.e. 99. Why? Well, if a number is divisible by a number larger than its square-root, it will also be divisible by the quotient of that division, which is necesaarily smaller than the square-root. And since we have already tried (and failed) to divide by those smaller numbers, there is no need to keep going...&lt;br /&gt;&lt;br /&gt;The resulting code is very similar to the previous one:&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;from time import time&lt;br /&gt;from math import sqrt&lt;br /&gt;&lt;br /&gt;def primeList2(n, verbose = True) :&lt;br /&gt;t = time()&lt;br /&gt;ret = []&lt;br /&gt;for j in range(2,n+1) :&lt;br /&gt;    jIsPrime = True&lt;br /&gt;    kMax = int(sqrt(j))&lt;br /&gt;    for k in range(2,kMax+1) :&lt;br /&gt;        if j % k == 0 :&lt;br /&gt;            jIsPrime = False&lt;br /&gt;            break&lt;br /&gt;    if jIsPrime :&lt;br /&gt;        ret += [j]&lt;br /&gt;&lt;br /&gt;if verbose :&lt;br /&gt;    print "Calculated primes to",n,"in",time()-t,"sec."&lt;br /&gt;&lt;br /&gt;return ret&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Do try it, and feel the thrill of the new speed of the algorithm. If you are after all primes below 10,000, this new function will probably get them for you... a hundred times faster!!! If you try it for larger numbers, you will find even better speed increases, because the time required by our algorithm now grows with n&lt;sup&gt;1.4&lt;/sup&gt;.&lt;br /&gt;&lt;br /&gt;But we are still doing a lot of superfluous checking. Think again of 9973. Once we have tried to divide it by 2 and failed, there is no point in checking with 4, 6, 8 or any other multiple of 2. So yes, we could double the speed of our algorithm by checking only odd numbers, but lets spend a little more time thinking before going back to coding... Because, after failing with 2, once we turn our attention to 3 and again fail, what's the point in trying 6, 9, 12 or any other multiple of 3? If you keep the reasoning going, it becomes obvious that you only need to do trial division by prime numbers, since by the time we test whether a composite number divides 9973, we have already tested all its prime factors, and if those have failed, this one will as well.&lt;br /&gt;&lt;br /&gt;Now wait a minute! Isn't finding whether a number is prime or not precisely what we are after? How are we going to figure out what numbers to do trial division with? Well, we already saw in our first optimization that our division trials only need to go up to the square root of the number being tested, so we only need to know the first prime number, 2, and afterwards we can use the list of prime numbers that we are building to generate the additional items... The code to do that would look something like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: py"&gt;&lt;br /&gt;from time import time&lt;br /&gt;from math import sqrt&lt;br /&gt;&lt;br /&gt;def primeList3(n, verbose = True) :&lt;br /&gt;   t = time()&lt;br /&gt;   ret = []&lt;br /&gt;   for j in range(2,n+1) :&lt;br /&gt;       jIsPrime = True&lt;br /&gt;       kMax = sqrt(j)&lt;br /&gt;       for k in ret :&lt;br /&gt;           if k &gt; kMax :&lt;br /&gt;               break&lt;br /&gt;           if j % k == 0 :&lt;br /&gt;               jIsPrime = False&lt;br /&gt;               break&lt;br /&gt;       if jIsPrime :&lt;br /&gt;           ret += [j]&lt;br /&gt;&lt;br /&gt;   if verbose :&lt;br /&gt;       print "Calculated primes to",n,"in",time()-t,"sec."&lt;br /&gt;&lt;br /&gt;   return ret&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;If you test this code you'll surely notice the new speed increase. This last optimization doesn't make it a hundred times faster, but on my computer the new code is 3.5 faster than the previous one when calculating all primes below 100,000 and 5.5 times faster when calculating all primes below 1,000,000. And again, what really makes the new code more efficient is not that 4x increase in speed, but the fact that, the larger our input number gets, the better the new code is. It seems that now time required grows with n&lt;sup&gt;1.25&lt;/sup&gt;...&lt;br /&gt;&lt;br /&gt;THis last version holds the fundamental ideas of really fast versions, i.e. skipping multiples of primes, but still relies on the slow ans tie consuming operation of trial division. Getting rid of it is the next optimization, which we will see in the next post.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/835341608950140555-7631306534593538485?l=numericalrecipes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://numericalrecipes.blogspot.com/feeds/7631306534593538485/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://numericalrecipes.blogspot.com/2009/03/prime-numbers_04.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/7631306534593538485'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/7631306534593538485'/><link rel='alternate' type='text/html' href='http://numericalrecipes.blogspot.com/2009/03/prime-numbers_04.html' title='Prime Numbers 1. The Wrong Way'/><author><name>Jaime</name><uri>http://www.blogger.com/profile/02831887559711602902</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://1.bp.blogspot.com/_47tBuP0my9o/Sa6DmpICr3I/AAAAAAAAAGE/rGBLWTTlODU/S220/318462932_a2fef46344_m.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-835341608950140555.post-7090547423420650519</id><published>2009-03-04T18:36:00.013+01:00</published><updated>2009-03-15T23:45:51.148+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='general'/><title type='text'>Excusatio Non Petita</title><content type='html'>The year probably was 1994, so I guess its understandable that I don't exactly recall how did I come across a copy of &lt;a href="http://www.amazon.com/Numerical-Recipes-C-Scientific-Computing/dp/0521431085/ref=sr_1_9?ie=UTF8&amp;amp;s=books&amp;amp;qid=1236206282&amp;amp;sr=8-9"&gt;Numerical Recipes in C: The Art of Scientific Computing&lt;/a&gt;. But while skimming through the pages, I eventually got to the part on evaluating polynomials, and read something that struck me very deeply. The paragraph that described what I now know is &lt;a href="http://en.wikipedia.org/wiki/Horner_scheme"&gt;Horner's scheme&lt;/a&gt; read as follows:&lt;br /&gt;&lt;blockquote&gt;We assume that you know enough never to evaluate a polynomial this way:&lt;br /&gt;&lt;br /&gt;p=c[0]+c[1]*x+c[2]*x*x+c[3]*x*x*x +c[4]*x*x*x*x;&lt;br /&gt;&lt;br /&gt;or (even worse!),&lt;br /&gt;&lt;br /&gt;p=c[0]+c[1]*x+c[2]*pow(x,2.0)+c[3]*pow(x,3.0)+c[4]*pow(x,4.0);&lt;br /&gt;&lt;br /&gt;Come the (computer) revolution, all persons found guilty of such criminal behavior will be summarily executed, and their programs won’t be! It is a matter of taste, however, whether to write&lt;br /&gt;&lt;br /&gt;p=c[0]+x*(c[1]+x*(c[2]+x*(c[3]+x*c[4])));&lt;br /&gt;&lt;br /&gt;or&lt;br /&gt;&lt;br /&gt;p=(((c[4]*x+c[3])*x+c[2])*x+c[1])*x+c[0];&lt;/blockquote&gt;&lt;br /&gt;Boy was I guilty! Who would have ever thought there was another way of evaluating a polynomial than the obvious one? And that it would be so much more elegant and efficient?&lt;br /&gt;&lt;br /&gt;Would be nice if  it was just a polynomial thing, but of course it isn't, and the more complicated the math you are trying to get your computer to do, the larger the chance you are doing it terribly bad.  And although much has been written about algorithms, the gospel doesn't seem to be spreading too swiftly: as I am writing this, the first match for a search of "prime numbers python " that google returns is &lt;a href="http://www.gidforums.com/t-9440.html" target="_blank"&gt;this&lt;/a&gt;. And he is &lt;a href="http://pthree.org/2007/09/05/prime-numbers-in-python/" target="_blank"&gt;not alone&lt;/a&gt;...&lt;br /&gt;&lt;br /&gt;So what am I in for? The idea is to bridge the gap between straightforward brute force (a sin I have been as guilty as anyone else of) and the elegant simplicity of efficient code. Hopefully, this will allow me to escape the guillotine when the Jacobins take over...&lt;br /&gt;&lt;br /&gt;There are some simple rules that I intend to follow, at least until I decide not to:&lt;br /&gt;&lt;ol&gt;&lt;br /&gt; &lt;li&gt;&lt;strong&gt;Uncomplicated complexity.&lt;/strong&gt; The math content will be kept reasonably simple. Or maybe simple isn't the word, as things may get utterly complex. But I will try to stay out of unnecessary complications, so a high school diploma should be all you need to come along on the ride...&lt;/li&gt;&lt;br /&gt; &lt;li&gt;&lt;strong&gt;Plain python.&lt;/strong&gt; Sure, C++ is a zillion times faster, but python takes care of most gory details, and makes it easier to concentrate on the algorithm. Plus, it's so cool and trendy!&lt;/li&gt;&lt;br /&gt; &lt;li&gt;&lt;strong&gt;No libraries&lt;/strong&gt;. &lt;a href="http://www.sagemath.org/" target="_blank"&gt;Sage&lt;/a&gt;, &lt;a href="http://www.scipy.org/" target="_blank"&gt;SciPy&lt;/a&gt;, &lt;a href="http://pari.math.u-bordeaux.fr/" target="_blank"&gt;PARI&lt;/a&gt;, &lt;a href="http://www.qhull.org/" target="_blank"&gt;qhull&lt;/a&gt;, &lt;a href="http://www.fftw.org/" target="_blank"&gt;FFTW&lt;/a&gt;... whatever it is you are trying to achieve computationally, there is a faster way than replicating the code you find in this blog. And interesting as that may be, it would take a lot of the charm of writing this blog, if it turned into a description of somebody else's API. So yes, we will even code our own FFTs!&lt;/li&gt;&lt;br /&gt;&lt;/ol&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/835341608950140555-7090547423420650519?l=numericalrecipes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://numericalrecipes.blogspot.com/feeds/7090547423420650519/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://numericalrecipes.blogspot.com/2009/03/excusatio.html#comment-form' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/7090547423420650519'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/835341608950140555/posts/default/7090547423420650519'/><link rel='alternate' type='text/html' href='http://numericalrecipes.blogspot.com/2009/03/excusatio.html' title='Excusatio Non Petita'/><author><name>Jaime</name><uri>http://www.blogger.com/profile/02831887559711602902</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://1.bp.blogspot.com/_47tBuP0my9o/Sa6DmpICr3I/AAAAAAAAAGE/rGBLWTTlODU/S220/318462932_a2fef46344_m.jpg'/></author><thr:total>5</thr:total></entry></feed>
