2016-07-28

Contents

Infinite series and Python

Infinite series in Other Languages

Partial sums.

Consecutive sums

Bug Fixes

Merging Streams

Generating Primes

Pipe Connection

Pipe Teeing

Portability

Stream Merge

Alternative Solutions

I chanced upon an interesting puzzle:

Find the smallest number that can be expressed as the sum of 5, 17, 563, 641 consecutive prime numbers, and is itself a prime number.


Infinite series and Python

The prime numbers famously form an infinite series and my first thought was to tackle this puzzle using Python iterators and generators. Courtesy of the Python Cookbook, I already had a couple of useful recipes:

Both these functions merit a closer look for the cunning use they make of standard containers, but we’ll defer this inspection until later. In passing, note that stream_merge()’s docstring suggests we might try using it as basis for primes():

form the series of composite (non-prime) numbers by merging the streams formed by multiples of prime numbers;

the primes remain when you remove these composites from the series of natural numbers.

This scheme is hardly original — it’s a variant of Eratosthenes’ famous sieve — but if you look carefully you’ll notice the self-reference. Unfortunately recursive definitions of infinite series don’t work well with Python[1], hence primes() requires a little more finesse. We’ll take a look at it later.

Moving on then, to solve the original puzzle we need a consecutive sum filter. This takes a stream of numbers and yields a stream of consecutive sums of these numbers:

Here we visualise the summed elements as lying within a sliding window: each time we slide the window an element gets added to the top and an element gets removed from the bottom, and we adjust csum accordingly.

So, now we have:

the series of prime numbers, primes()

a stream_merge() connector

a consecutive_sum() filter

The remaining stream adaptors come from the standard itertools module. Note that the stream_merge() works here since all the consecutive sum series are strictly increasing. Note also that the stream of prime numbers can be treated as consecutive_sum(s=primes(), n=1), handling the “and is itself a prime number” requirement.

Here’s a picture of how these stream tools link up to solve this particular puzzle. The great thing is that we can reconnect these same tools to solve a wide range of puzzles, and indeed more practical processing tasks. To use the common analogy, we direct data streams along pipes.


Infinite series in Other Languages

Python is the high-level language I find most convenient most of the time, which explains why I reached for it first. It’s an increasingly popular language, which helps explain why it I didn’t need to write the tricky parts of my solution from scratch: they’d already been done. Python is also a language which makes compromises. Having used Python to find a solution to the puzzle I wondered if there wasn’t some other language better suited to this kind of problem.

Haskell makes no compromises when it comes to functional programming. Its lazy evaluation and guilt-free recursion make it a perfect fit for this kind of puzzle — but my Pythonic approach of teeing, filtering and merging streams made me think first of the Unix Shell. Now, I use Bash every day and page through its manual at least once a week. Scripting appeals and I’m comfortable at the command line. How hard could it be to solve this puzzle using Bash? After all, I already knew the answer! Let’s give it a go.

Partial sums.

Here’s a simple shell function to generate partial sums. I’ve used awk, a little language I gave up on a long time ago in favour of more rounded scripting languages like Perl and then Python. Now I look at it again, it seems to fill a useful gap. Awk processes a file sequentially, applying pattern-action rules to each line, a processing pattern which I’ve reinvented less cleanly many times. Despite my rediscovery of awk, I’ll be keeping its use strongly in check in what follows.

Much like Perl, awk guesses what you want to do. Here, it conjures the summation variable, s, into existence, assigning it a default initial value of 0. (Good guess!) Since we’re doing arithmetic awk converts the first field of each input line into a number. We can test psum by using jot to generate the sequence 1, 2, 3, 4, 5 (on a Linux platform use seq instead of jot).

Consecutive sums

You may be wondering why we’ve bothered creating this partial sum filter since it’s the sums of consecutive elements we’re after, rather than the sum of the series so far. Well, notice that if P[i] and P[i+n] are two elements from the series of partial sums of S, then their difference, P[i+n] - P[i], is the sum of the n consecutive elements from S.

So to form an n-element consecutive sum series we can tee the partial sums streams, advance one of these by n, then zip through them in parallel finding their differences. An example makes things clear:

Here, jot 5 generates the sequence 1, 2, 3, 4, 5, which psum progressively accumulates to 1, 3, 6, 10, 15. We then tee this partial sum series through two pipes: the first, pipe, is an explicitly created named pipe created by mkfifo, the second is implicitly created by the pipeline operator, |. The remainder of the command line delays one series by one (note that tail numbers lines from 1, not 0, so tail -n +1 is the identity filter) then pastes the two series back together[2].

By appending a single awk action to the pipeline we get a consecutive sum series.

The output 2, 3, 4, 5 is the series of consecutive sums of length 1 taken from the original series 1, 2, 3, 4, 5. The trailing 15 and the 1 missed from the start are edge case problems, and easily corrected.

Accumulating an increasing series of numbers in order to find the differences between elements lying a given distance apart on this series isn’t a very smart idea on a computer with a fixed word-size, but it’s good to know (e.g.) that awk doesn’t stop counting at 32 bits.

Exactly if and when awk stops counting, I’m not sure. The documentation doesn’t say and I haven’t looked at the source code.

Bug Fixes

Let’s capture these tiny functions and name them. Here, then, are revised psum() and sdiff() filters. The edge case problems should now be fixed.

A quick test:

The output is, as expected, the series of sums of consecutive triples taken from 1, 2, 3, 4, 5 (1+2+3, 2+3+4, 3+4+5).

There’s a more pernicious bug, though. Sdiff can’t handle an infinite series, so it’s of limited use as a pipeline tool. For example, if we stream it the series 0, 1, 2, … (generated here as the partial sums of the series 1, 1, 1, …) nothing gets output and we have to interrupt the process.

I found a way to work around this problem by redirecting the teed stream to a subshell which itself redirects into a named pipe.

As you can see this gets data flowing once again, but I’m already out of my comfort zone: I couldn’t tell you why exactly this works but the preceding version doesn’t.

(You can of course write a consecutive sum function directly in awk: here’s a version which leans hard on the “do what I mean” style of programming, accessing and deleting array entries which haven’t even been set.

For this article I’ve avoided pushing the consecutive sum job awk’s way because I’m more interested in figuring out how this pipe-connection works for non-trivial cases. Any advice would be welcome!)

Merging Streams

The Unix shell merges streams rather more succinctly than Python. Sort -m does the job directly. Note that a standard sort cannot yield any output until all its inputs are exhausted, since the final input item might turn out to be the one which should appear first in the output. Merge sort, sort -m can and does produce output without delay[3].

Generating Primes

No doubt it’s possible to generate the infinite series of prime numbers using native Bash code, but I chose to reuse the Python Cookbook recipe for the job.

primes

This is a subtle little program which makes clever use of Python’s native hashed array container, the dictionary. In this case dictionary values are the primes less than n and the keys are composite multiples of these primes. The loop invariant, roughly speaking, is that the dictionary values are the primes less than n, and the corresponding keys are the lowest multiples of these primes greater than or equal to n. It’s a lazy, recursion-free variant of Eratosthenes’ sieve.

For the purposes of this article the important things about this program are:

it generates an infinite series of numbers to standard output[4], making it a good source for a shell pipeline;

by making it executable and adding the usual shebang incantation, we can invoke this Python program seamlessly from the shell.

Pipe Connection

Recall the original puzzle:

Find the smallest number that can be expressed as the sum of 5, 17, 563, 641 consecutive prime numbers, and is itself a prime number.

First, let’s check the connections by solving a simpler problem which we can manually verify: to find prime numbers which are also the sum of 2 consecutive primes. As we noted before, this is the same as finding primes numbers which are the consecutive sums of 1 and 2 primes.

In one shell window we create a couple of named pipes, c.1 and c.2, which we’ll use to stream the consecutive sum series of 1 and 2 primes respectively. The results series comprises the duplicates when we merge these pipes.

Shell 1

In another shell window, stream data into c.1 and c.2:

Shell 2

In the first window we see the single number 5, which is the first and only prime number equal to the sum of two primes.

Prime numbers equal to the sum of three consecutive primes are more interesting. In each shell window recall the previous commands and switch the 2s to 3s (a simple command history recall and edit, ^2^3^, does the trick). The merged output now looks like this:

We can check the first few values:

At this point we’re confident enough to give the actual puzzle a try. Start up the solutions stream.

Here, we use a standard shell script set intersection recipe: uniq -c groups and counts repeated elements, and the grep pattern matches those numbers common to all five input streams.

Now we can kick off the processes which will feed into the consecutive sum streams, which sort is waiting on.

Sure enough, after about 15 seconds elapsed time[5], out pops the result:

15 seconds seems an eternity for arithmetic on a modern computer (you could start up a word processor in less time!), and you might be inclined to blame the overhead of all those processes, files, large numbers, etc. In fact it took around 6 seconds for the Python program simply to generate prime numbers up to 7002221, and my pure Python solution ran in 9 seconds.

Pipe Teeing

5 × primes | sum

This shell solution works but I’m not happy with it. The source loop spawns 5 separate instances of primes and pipes them all through psum. I don’t care about giving the computer more to do than necessary, but I do wish I could figure out the details of this dataflow plumbing. What I’d like to do is split the output of primes | psum five ways, connecting each resulting stream to an instance of sdiff. Something like the following:

This doesn’t work

When I run this sequence of commands nothing happens: by which I mean something blocks and nothing gets through to sort. Again, I’m out of my depth and not sure what’s going on — any advice would be welcome. The shell makes it all too easy to experiment, and I reckon I’ve already exhausted the obvious permutations of wax, tac, crunch, wane, amp, zap, tic, pretzel.

Portability

One of the most convenient things about Python is its portability. I don’t mean “portable so long as you conform to the language standard” or “portable if you stick to a subset of the language” — I mean that a Python program works whatever platform I use without me having to worry about it. In fact I’m guilty of taking this portability for granted, and was surprised to discover a program of mine failed on Windows (the fcntl module is Unix only).

Non-portability put me off the Unix shell when I first encountered it: there seemed too many details, too many platform differences — which shell are you using? which extensions? which implementation of the core utilities, etc, etc? Readily available and well-written documentation didn’t help much here: generally I want the shell to just do what I mean, which is why I switched so happily to Perl when I discovered it.

Since then this situation has, for me, improved in many ways. Non-Unix platforms are declining as are the different flavours of Unix. Bash seems to have become the standard shell of choice and Cygwin gets better all the time. GNU coreutils predominate. As a consequence I’ve forgotten almost all the Perl I ever knew and am actively rediscovering the Unix shell.

Writing this article, though, I was reminded of the platform dependent behaviour which used to discourage me. On a Linux platform close to hand I had to use seq instead of jot, and awk formatted large integers in a scientific form with a loss of precision.

Loss of precision

On OS X the same command outputs 10000000001. I couldn’t tell you which implementation is more correct. The fix is to explicitly format these numbers as decimal integers, but the danger is that the shell silently swallows these discrepancies and you’ve got a portability problem you don’t even notice.

Precision recovered

Stream Merge

I mentioned stream_merge() at the start of this article, a general purpose function written by Raymond Hettinger which I originally found in the Python Cookbook. As with the prime number generator, you might imagine the merge algorithm to be recursively defined:

to merge a pair of streams, take items from the first which are less than the head of the second, then swap;

to merge N streams, merge the first stream with the merged (N-1) rest.

Again the Python solution does it differently, this time using a heap as a priority queue of items from the input streams. It’s ingenious and efficient. Look how easy it is in Python to shunt functions and pairs in and out of queues.

A more sophisticated version of this code has made it into the Python standard library, where it goes by the name of heapq.merge (I wonder why it wasn’t filed in itertools?)

Alternative Solutions

As usual Haskell wins the elegance award, so I’ll quote in full a solution built without resorting to cookbookery which produces the (correct!) answer in 20 seconds.

[1] CPython, more precisely — I don’t think anything in the Python language itself prohibits tail recursion. Even using CPython, yet another recipe from the online Python Cookbook explores the idea of an @tail_recursion decorator.

[2] Tail is more commonly used to yield a fixed number of lines from the end of the file: by prefixing the line count argument with a + sign, it skips lines from the head of the file. The GNU version of head can similarly be used with a - prefix to skip lines at the tail of a file. The notation is {compact,powerful,subtle,implementation dependent}.

[3] Sort -m is a sort which doesn’t really sort — its inputs should already be sorted — rather like the +n option turning tail on its head.

[4] The series is infinite in theory only: at time n the number of items in the has_prime_factors dictionary equals the number of primes less than n, and each key in this dictionary is larger than n. So resource use increases steadily as n increases.

[5] I used a MacBook laptop used to run these scripts.

Show more