# Enigmatic Code

Programming Enigma Puzzles

## Enigma 1539: Board with primes?

From New Scientist #2702, 4th April 2009 [link]

As I have mentioned in a previous Enigma puzzle, a “Snakes and Ladders” board consists of a 10-by-10 grid of squares. In row 1 (at the bottom) the squares are numbered from 1 to 10 from left to right. Then in row 2 the squares are numbered 11 to 20 from right to left. In row 3 they are 21 to 30 from left to right again, and so on, ending up at square 100 in column 1 and row 10.

I have been cutting up such a board. I have cut out a rectangle consisting precisely of some of its squares. It runs from a prime-numbered row of the original board to a higher prime-numbered row inclusive, and it runs from a prime-numbered column to a higher prime-numbered column inclusive. Furthermore, the total of all the numbers in my rectangle is a prime.

What is that total?

[enigma1539]

### 2 responses to “Enigma 1539: Board with primes?”

1. Jim Randell 17 April 2012 at 8:36 am

Here’s my original Perl code. It runs in 13ms.

```use strict;

use Enigma qw/prime/;

# primes below 10
my @PRIMES = qw/2 3 5 7/;

my (\$R1, \$R2, \$C1, \$C2, \$R, \$C, \$SUM);

for \$R1 (@PRIMES) {
for \$R2 (@PRIMES) {
next unless \$R1 < \$R2;

for \$C1 (@PRIMES) {
for \$C2 (@PRIMES) {
next unless \$C1 < \$C2;

\$SUM = 0;
for \$R (\$R1..\$R2) {
for \$C (\$C1..\$C2) {
\$SUM += (\$R % 2 ? 10 * (\$R - 1) + \$C : 10 * \$R + 1 - \$C);
}
}
next unless prime(\$SUM);

print "R[\$R1,\$R2] x C[\$C1,\$C2] = \$SUM\n";
}
}
}
}
```

Solution: The sum of the numbers in the rectangle is 449.

• Jim Randell 17 April 2012 at 8:37 am

And here’s my Python solution. It runs in 37ms.

```from itertools import combinations, product
from enigma import irange, chunk, is_prime, printf

# primes below 10
primes = (2, 3, 5, 7)

# pairs of primes s.t. a < b
pairs = list(sorted(x) for x in combinations(primes, 2))

# make a grid for the board
grid = list(chunk(irange(1, 100), 10))
for i in irange(1, 9, step=2):
grid[i] = list(reversed(grid[i]))

# compute sums
for (cs, rs) in product(pairs, repeat=2):
s = sum(sum(grid[r][cs[0] - 1:cs[1]]) for r in irange(rs[0] - 1, rs[1] - 1))
if not prime(s): continue
printf("sum={s} rows={rs} cols={cs}")
```