Of course, such a prime has to match the digits that are already in the square. When all twelve slots have been filled with primes we have a solution. This programming technique is known as backtracking . One thing that we have not discussed is the order in which we fill the slots. To reduce the number of possibilities as much as possible, we should try to fill slots for which as many digits as possible are already known, because this restricts the number of primes that will fit there.
Many orders are possible.
Since the first digit of each slot is known, we can restrict attention to primes from the table that start with that digit. All that now remains is to fill the slots. For each slot we write a procedure that has the obligation to fill that slot in all possible ways and for each successful filling to call the procedure dealing with the next slot. All primes with this first digit are traversed by the for-loop. Only the primes without zeroes are filled in, after which V1 continues.