### 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 http://www.math.ucdavis.edu/~dean/puzzles/primemaze.html. 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 primemaze.pl. Here it is.

```node(a). node(b). node(c). node(d). node(e).
node(f). node(g). node(h). node(i). node(j).
node(k). node(l). node(m). node(n). node(o).
node(p). node(q). node(r). node(s). node(t).
node(u). node(v). node(w).

prime(2).
prime(N) :- N>1, N mod 2 =\=0, primetest(N,3).
primetest(N,M) :- N>M, N mod M =\= 0, K is M+2, primetest(N,K).
primetest(N,N).

path(A,P,B,Q,[[A,P],[B,Q]]) :- R is Q-P, link(A,B,R).
path(A,P,B,Q,X) :- link(A,C,L), R is P+L, R< Q, prime(R), path(C,R,B,Q,Y), X=[[A,P]|Y].

solution(X,Q) :- prime(Q), node(A), path(A,0,A,Q,X).
solution(X) :- solutionsearch(X,3).
solutionsearch(X,Q) :- prime(Q),solution(X,Q).
solutionsearch(X,Q) :- R is Q+2, solutionsearch(X,R).
```
And here's a run illustrating how it works. First, a couple of lines to see how prime and primetest work.
```0\$ gprolog
GNU Prolog 1.2.9
By Daniel Diaz
| ?- consult('primemaze.pl').
compiling /home/djoyce/public_html/cs170/primemaze.pl for byte code...
/home/djoyce/public_html/cs170/primemaze.pl compiled, 41 lines read - 12423 bytes written, 23 ms
yes
| ?- prime(3).
yes
| ?- prime(4).
no
| ?- prime(89).
yes
| ?- prime(91).
no
| ?- primetest(9,4).
yes
| ?- primetest(9,3).
no
| ?- prime(9).
no
| ?- solution(X).
X = [[b,0],[j,17],[s,23],[j,29],[i,37],[k,41],[q,53],[l,61],[i,67],[k,71],
[p,83],[t,89],[u,103],[p,107],[t,113],[u,127],[w,137],[v,139],[o,151],[v,163],
[n,167],[e,173],[n,179],[o,181],[v,193],[n,197],[o,199],[v,211],[o,223],[g,227],
[f,233],[o,239],[v,251],[o,263],[f,269],[e,271],[n,277],[v,281],[w,283],[u,293],
[t,307],[p,313],[u,317],[t,331],[p,337],[k,349],[i,353],[l,359],[q,367],[k,379],
[i,383],[l,389],[m,401],[r,409],[q,419],[k,431],[p,443],[t,449],[h,457],[c,467],
[d,479],[c,491],[a,499],[d,509],[b,523]]
?
\$```
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.