Computer Science 170
Analysis of Programming Languages

Spring 2003, Clark University
D Joyce

Primemaze, a prolog example

For a description of the Prime Maze problem of Dean Hickerson (Dept. Math, U.C.Davis), see his writeup on page 48 of the Mathematical Intelligencer or go directly to his page on the problem at The problem is to find a path from one town back to itself so that the distance travelled at each town along the way is a prime number. The article includes a graph of the 23 towns and distances between adjacent towns.

For instance, it's two units from town a to town b, 17 units from town b to town j, 10 units from town j to town m, so a path might start out a, b, j, m, since at b the distance travelled will be 2 (a prime number), at j the distance travelled will be 19 (which is prime), at m it will be 29 (also prime). The problem is to figure out what path with bring you back to where you started, and also to determine where to start.

A solution in the logic programming language prolog

The code for primemaze is stored in the file Here it is.

And here's a run illustrating how it works. First, a couple of lines to see how prime and primetest work. Note that it takes 50 ms just to see if there's a solution whose total length is 1009. It's not surprizing that a stack overflow occurs when searching for longer and longer solutions.

Back to the course page.