Prime triangle: Difference between revisions
→{{header|ALGOL 68}}: Slight simplification
(→{{header|Go}}: Updated in line with Phix example of which this is a translation.) |
(→{{header|ALGOL 68}}: Slight simplification) |
||
Line 20:
FI
OD;
prime pair[ a, 1 ] := FALSE;▼
prime pair[ a, b ] := prime[ a + b ]▼
OD;▼
# the numbers must alternate between even and odd in order for the sum to be prime #▼
INT result := IF current > 0 THEN current + 2▼
ELIF ODD i THEN 2▼
ELSE 3▼
FI;▼
WHILE IF result >= n THEN FALSE ELSE NOT prime pair[ i, result ] OR used[ result ] FI DO▼
result +:= 2▼
OD;▼
IF result >= n THEN 0 ELSE result FI▼
END # find next # ;▼
# returns the number of possible arrangements of the integers for a row in the prime triangle #
PROC count arrangements = ( INT n
IF n < 2 THEN # no solutions for n < 2 # 0
ELIF n < 4 THEN
# for 2 and 3. there is only 1 solution: 1, 2 and 1, 2, 3 #
FOR i TO n DO print( ( whole( i, -3 ) ) ) OD; print( ( newline ) )▼
FI;▼
1
ELSE
# 4 or more - must find the solutions #
[ 0 : n ]BOOL used;
[ 0 : n ]INT number;
# the triangle row must have 1 in the leftmost and n in the rightmost elements #▼
▲ # the numbers must alternate between even and odd in order for the sum to be prime #
FOR i FROM 0 TO n DO
used[
number[
OD;
▲ # the triangle row must have 1 in the leftmost and n in the rightmost elements #
number[
# find the intervening numbers and count the solutions #
INT count := 0;
INT p := 2;
WHILE p
INT
INT
▲ WHILE IF
▲ OD;
IF p = n - 1 THEN
# we are at the final number before n #
# found a solution #▼
count +:= 1;▼
print( ( whole( number[ i ], -3 ) ) )▼
# here will be a further backtrack as next is 0 ( there could only be one possible number at p - 1 ) #
FI;
IF next /= 0 THEN
# have a/another number that can appear at p #
used[
used[
number[
▲ # found a solution #
▲ count +:= 1;
▲ IF count = 1 AND print solution THEN
▲ print( ( whole( number[ i ], -3 ) ) )
▲ # backtrack for more solutions #
▲ number[ p ] := 0;
▲ p -:= 1
▲ FI
ELIF p <= 2 THEN
# no more solutions #
p :=
ELSE
# can't find a number for this position, backtrack #
used[ number[ p ] ] := FALSE;
number[ p ] :=
p -:= 1
FI
Line 110 ⟶ 94:
[ 2 : max number ]INT arrangements;
FOR n FROM LWB arrangements TO UPB arrangements DO
arrangements[ n ] := count arrangements( n
OD;
FOR n FROM LWB arrangements TO UPB arrangements DO
Line 116 ⟶ 100:
OD;
print( ( newline ) )
END</lang>
{{out}}
<pre>
|