Brainteaser 1457: All square
From The Sunday Times, 12th August 1990 [link]
Your task this week is to place a non-zero digit in each of the 16 squares shown:
When you’ve finished each of the four rows should read across as a four-figure perfect square, and each of the four columns should read down as a four-figure perfect square.
What is the sum of the 16 digits?
[teaser1457]

Jim Randell 8:00 am on 21 December 2023 Permalink |
The following run file executes in 112ms. (Internal runtime of the generated program is 23ms).
Run: [ @replit ]
Solution: The sum of the 16 digits is 56.
The completed grid is as follows:
LikeLike
GeoffR 6:21 pm on 21 December 2023 Permalink |
% A Solution in MiniZinc include "globals.mzn"; % A B C D % E F G H % I J K L % M N P Q var 1..9:A; var 1..9:B; var 1..9:C; var 1..9:D; var 1..9:E; var 1..9:F; var 1..9:G; var 1..9:H; var 1..9:I; var 1..9:J; var 1..9:K; var 1..9:L; var 1..9:M; var 1..9:N; var 1..9:O; var 1..9:P; var 1..9:Q; var 16..108:total; % UB = 2*45 + 18 set of int: sq4 = {n*n | n in 34..96}; % 97,98,99 have zeroes in squares, as do 32 and 33 % ROWS var 1156..9216:ABCD == 1000*A + 100*B + 10*C + D; var 1156..9216:EFGH == 1000*E + 100*F + 10*G + H; var 1156..9216:IJKL == 1000*I + 100*J + 10*K + L; var 1156..9216:MNPQ == 1000*M + 100*N + 10*P + Q; % COLUMNS var 1156..9216:AEIM == 1000*A + 100*E + 10*I + M; var 1156..9216:BFJN == 1000*B + 100*F + 10*J + N; var 1156..9216:CGKP == 1000*C + 100*G + 10*K + P; var 1156..9216:DHLQ == 1000*D + 100*H + 10*L + Q; % Last digit of squares is 1,4,5,6 or 9. set of int: dig_end = {1,4,5,6,9}; constraint sum([D in dig_end, H in dig_end, L in dig_end, Q in dig_end]) == 4; constraint sum([M in dig_end, N in dig_end, P in dig_end]) == 3; constraint sum([ABCD in sq4, EFGH in sq4, IJKL in sq4, MNPQ in sq4, AEIM in sq4, BFJN in sq4, CGKP in sq4, DHLQ in sq4]) = 8; constraint total = A+B+C+D+E+F+G+H+I+J+K+L+M+N+P+Q; solve satisfy; output ["Total of all digits = " ++ show(total) ++ "\n" ++ show(ABCD) ++ "\n" ++ show(EFGH) ++ "\n" ++ show(IJKL) ++ "\n" ++ show(MNPQ)]; % Total of all digits = 56 % 2116 % 1225 % 1296 % 6561 % ---------- % ========== % Finished in 442msec.LikeLike
Frits 12:58 pm on 22 December 2023 Permalink |
Using permutations is a lot slower (1 second with PyPy).
from itertools import permutations sqs = {x2 for x in range(32, 100) if '0' not in (x2 := str(x * x))} for hor in permutations(sqs, 4): # check columns, transpose the permutation to get the columns if any(''.join(x) not in sqs for x in (zip(*hor))): continue for h in hor: print(h) print("\nanswer:", sum(int(d) for h in hor for d in h))LikeLike