Sum and product puzzle: Difference between revisions

Added various BASIC dialects (BASIC256 and Gambas)
(Added various BASIC dialects (BASIC256 and Gambas))
 
(28 intermediate revisions by 11 users not shown)
Line 1:
{{task}}
;Task:
{{task heading}}
Solve the "<i>Impossible Puzzle</i>":
 
Line 55:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F counter(arr)
DefaultDict[Int, Int] d
L(a) arr
Line 81:
V final_pairs = p_pairs.filter((a, b) -> :sum_counts[a + b] == 1)
 
print(final_pairs)</langsyntaxhighlight>
 
{{out}}
<pre>
[(4, 13)]
</pre>
 
=={{header|ALGOL 68}}==
<syntaxhighlight lang="algol68">
BEGIN # solve the sum and product puzzle: find X, Y where 1 < X < Y; X + Y <= 100 #
# mathematician S knows X + Y and P knows X * Y #
# S says P doesn't know X and Y, P says they now know X and Y which leads S #
# to also know X and Y #
# which leads to the following (from the task) #
# 1: For every possible sum decomposition of the number X+Y, #
# the product has in turn more than one product decomposition #
# 2: The number X*Y has only one product decomposition for which 1: is true #
# 3: The number X+Y has only one sum decomposition for which 2: is true #
 
# determine the possible sums and products and count their occurances #
INT max n = 98, min n = 2;
[ 0 : max n * max n ]INT s count, p count;
[ min n : max n, min n : max n ]BOOL candidate;
FOR x FROM LWB p count TO UPB p count DO p count[ x ] := s count[ x ] := 0 OD;
FOR x FROM min n TO max n DO FOR y FROM min n TO max n DO candidate[ x, y ] := FALSE OD OD;
FOR x FROM min n TO max n - min n DO
FOR y FROM x + 1 TO max n - x DO
s count[ x + y ] +:= 1;
p count[ x * y ] +:= 1
OD
OD;
 
# shows the count of the candidates #
PROC show candidates = ( STRING stage )VOID:
BEGIN
INT c count := 0;
FOR x FROM min n TO max n DO
FOR y FROM min n TO max n DO IF candidate[ x, y ] THEN c count +:= 1 FI OD
OD;
print( ( stage, " ", whole( c count, - 5 ), " candidate", IF c count = 1 THEN "" ELSE "s" FI, newline ) )
END # show candidates # ;
 
# checks 1: is TRUE for x plus y, returns TRUE if it is, FALSE otherwose #
PROC all sums have multiple product decompositions = ( INT x plus y )BOOL:
BEGIN
BOOL all multiple p := TRUE;
FOR x FROM min n TO x plus y OVER 2 WHILE all multiple p DO
INT y = x plus y - x;
IF y > x AND y <= max n THEN
# x, y is a sum decomposition of x plus y #
IF candidate[ x, y ] THEN all multiple p := all multiple p AND p count[ x * y ] > 1 FI
FI
OD;
all multiple p
END # all sums have multiple product decompositions # ;
 
# checks 2: is TRUE for x times y, returns TRUE if it is, FALSE otherwose #
PROC only one product decomposition = ( INT x times y )BOOL:
BEGIN
INT multiple p := 0;
FOR x FROM min n TO ENTIER sqrt( x times y ) DO
IF x times y MOD x = 0 THEN
INT y = x times y OVER x;
IF y > x AND y <= max n THEN
# x, y is a product decomposition of x times y #
IF candidate[ x, y ] THEN
IF all sums have multiple product decompositions( x + y ) THEN
multiple p +:= 1
FI
FI
FI
FI
OD;
multiple p = 1
END # only one product decomposition # ;
 
# start off with all min n .. max n as candidates #
FOR x FROM min n TO max n DO
FOR y FROM x + 1 TO max n DO
IF x + y <= 100 THEN candidate[ x, y ] := TRUE FI
OD
OD;
show candidates( "Sum and product puzzle " );
 
# Statement 1: S says P doesn't know X and Y #
FOR x plus y FROM min n TO max n + min n DO
IF NOT all sums have multiple product decompositions( x plus y ) THEN
FOR x FROM min n TO x plus y OVER 2 DO
INT y = x plus y - x;
IF y > x AND y <= max n THEN candidate[ x, y ] := FALSE FI
OD
FI
OD;
show candidates( "After statement 1 " );
 
# Statement 2: P says they now know X and Y #
FOR x times y FROM min n * ( min n + 1 ) TO max n * max n DO
IF NOT only one product decomposition( x times y ) THEN
FOR x FROM min n TO ENTIER sqrt( x times y ) DO
IF x times y MOD x = 0 THEN
INT y = x times y OVER x;
IF y > x AND y <= max n THEN candidate[ x, y ] := FALSE FI
FI
OD
FI
OD;
show candidates( "After statement 2 " );
 
# Statement 3: S says they now also know X and Y, check 3: #
FOR x plus y FROM min n TO max n + min n DO
INT multiple s := 0;
FOR x FROM min n TO x plus y OVER 2 DO
INT y = x plus y - x;
IF y > x AND y <= max n THEN
# x, y is a sum decomposition of x plus y #
IF candidate[ x, y ] THEN
IF only one product decomposition( x * y ) THEN multiple s +:= 1 FI
FI
FI
OD;
IF multiple s /= 1 THEN
FOR x FROM min n TO x plus y OVER 2 DO
INT y = x plus y - x;
IF y > x AND y <= max n THEN candidate[ x, y ] := FALSE FI
OD
FI
OD;
show candidates( "After statement 3 " );
 
print( ( newline, "solution: " ) );
FOR x FROM min n TO max n DO
FOR y FROM min n TO max n DO
IF candidate[ x, y ] THEN print( ( whole( x, 0 ), ", ", whole( y, 0 ), newline ) ) FI
OD
OD
 
END
</syntaxhighlight>
{{out}}
<pre>
Sum and product puzzle 2352 candidates
After statement 1 145 candidates
After statement 2 86 candidates
After statement 3 1 candidate
 
solution: 4, 13
</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f SUM_AND_PRODUCT_PUZZLE.AWK
BEGIN {
Line 153 ⟶ 294:
return(1)
}
</syntaxhighlight>
</lang>
<p>Output:</p>
<pre>
17 (4+13)
</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">for s = 2 to 100
a = satisfies_statement3(s)
if a <> 0 then print s & " (" & a & "+" & s - a & ")"
next s
end
 
function is_prime(x)
if x <= 1 then return false
for i = 2 to sqr(x)
if x mod i = 0 then return false
next i
return True
end function
 
function satisfies_statement1(s)
for a = 2 to s \ 2
if is_prime(a) and is_prime(s - a) then return false
next a
return true
end function
 
function satisfies_statement2(p)
winner = 0
for i = 2 to sqr(p)
if p mod i = 0 then
j = p \ i
if j < 2 or j > 99 then continue for
if satisfies_statement1(i + j) then
if winner then return false
winner = 1
end if
end if
next i
return winner
end function
 
function satisfies_statement3(s)
if not satisfies_statement1(s) then return false
winner = 0
for a = 2 to s \ 2
b = s - a
if satisfies_statement2(a * b) then
if winner then return false
winner = a
end if
next a
return winner
end function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|Gambas}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">Function is_prime(x As Integer) As Boolean
If x <= 1 Then Return False
For i As Integer = 2 To Sqr(x)
If x Mod i = 0 Then Return False
Next
Return True
End Function
 
Function satisfies_statement1(s As Integer) As Boolean
For a As Integer = 2 To s \ 2
If is_prime(a) And is_prime(s - a) Then Return False
Next
Return True
End Function
 
Function satisfies_statement2(p As Integer) As Integer
Dim winner As Integer = 0
For i As Integer = 2 To Sqr(p)
If p Mod i = 0 Then
Dim j As Integer = p \ i
If j < 2 Or j > 99 Then Continue
If satisfies_statement1(i + j) Then
If winner Then Return False
winner = 1
End If
End If
Next
Return winner
End Function
 
Function satisfies_statement3(s As Integer) As Integer
If Not satisfies_statement1(s) Then Return False
Dim winner As Integer = 0
For a As Integer = 2 To s \ 2
Dim b As Integer = s - a
If satisfies_statement2(a * b) Then
If winner Then Return False
winner = a
End If
Next
Return winner
End Function
 
Public Sub Main()
For s As Integer = 2 To 100
Dim a As Integer = satisfies_statement3(s)
If a <> 0 Then Print s; " ("; a; "+"; s - a; ")"
Next
End </syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
=={{header|C}}==
{{trans|C#}}
<langsyntaxhighlight lang="c">#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
Line 443 ⟶ 703:
free_list(&candidates);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>2352 candidates
Line 453 ⟶ 713:
=={{header|C++}}==
{{trans|C}}
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <map>
Line 609 ⟶ 869:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>2352 candidates
Line 618 ⟶ 878:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Collections.Generic;
Line 657 ⟶ 917:
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 669 ⟶ 929:
=={{header|Common Lisp}}==
===Version 1===
<langsyntaxhighlight lang="lisp">
;;; Calculate all x's and their possible y's.
(defparameter *x-possibleys*
Line 758 ⟶ 1,018:
(statement-2
(statement-1b *x-possibleys*)))) ;; => ((PRODUCT . 52) (SUM . 17) (Y . 13) (X . 4))
</syntaxhighlight>
</lang>
 
===Version 2===
<langsyntaxhighlight lang="lisp">
;;; Algorithm of Rosetta code:
 
Line 813 ⟶ 1,073:
 
(find-xy *all-possible-pairs*) ;; => ((4 13))
</syntaxhighlight>
</lang>
 
=={{header|D}}==
{{trans|Scala}}
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.range, std.typecons;
 
Line 833 ⟶ 1,093:
const s3 = s2.filter!(p => mulEq(p).setIntersection(s2).walkLength == 1).array;
s3.filter!(p => sumEq(p).setIntersection(s3).walkLength == 1).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[const(Tuple!(int, int))(4, 13)]</pre>
 
With an older version of the LDC2 compiler replace the <code>cartesianProduct</code> line with:
<syntaxhighlight lang="d">
<lang d>
const s1 = iota(1, 101).map!(x => iota(1, 101).map!(y => tuple(x, y))).joiner
</syntaxhighlight>
</lang>
The <code>.array</code> turn the lazy ranges into arrays. This is a necessary optimization because D lazy Ranges aren't memoized as Haskell lazy lists.
 
Line 847 ⟶ 1,107:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Puzzle do
def sum_and_product do
s1 = for x <- 2..49, y <- x+1..99, x+y<100, do: {x,y}
Line 870 ⟶ 1,130:
end
 
Puzzle.sum_and_product</langsyntaxhighlight>
 
{{out}}
Line 879 ⟶ 1,139:
=={{header|Factor}}==
A loose translation of D.
<langsyntaxhighlight lang="factor">USING: combinators.short-circuit fry kernel literals math
math.ranges memoize prettyprint sequences sets tools.time ;
IN: rosetta-code.sum-and-product
Line 903 ⟶ 1,163:
[ s2 [ mul-eq ] [ sum-eq ] [ only-1 ] bi@ . ] time ;
 
MAIN: sum-and-product</langsyntaxhighlight>
{{out}}
<pre>
Line 909 ⟶ 1,169:
Running time: 0.241637693 seconds
</pre>
 
=={{header|FreeBASIC}}==
{{trans|AWK}}
Runs in 0.001s
<syntaxhighlight lang="vbnet">Function is_prime(x As Integer) As Boolean
If x <= 1 Then Return False
For i As Integer = 2 To Sqr(x)
If x Mod i = 0 Then Return False
Next i
Return True
End Function
 
Function satisfies_statement1(s As Integer) As Boolean
For a As Integer = 2 To s \ 2
If is_prime(a) And is_prime(s - a) Then Return False
Next a
Return True
End Function
 
Function satisfies_statement2(p As Integer) As Integer
Dim As Integer i, j
Dim winner As Integer = 0
For i = 2 To Sqr(p)
If p Mod i = 0 Then
j = p \ i
If j < 2 Or j > 99 Then Continue For
If satisfies_statement1(i + j) Then
If winner Then Return False
winner = 1
End If
End If
Next i
Return winner
End Function
 
Function satisfies_statement3(s As Integer) As Integer
Dim As Integer a, b
If Not satisfies_statement1(s) Then Return False
Dim winner As Integer = 0
For a = 2 To s \ 2
b = s - a
If satisfies_statement2(a * b) Then
If winner Then Return False
winner = a
End If
Next a
Return winner
End Function
 
Dim As Integer s, a
For s = 2 To 100
a = satisfies_statement3(s)
If a <> 0 Then
Print s & " (" & a & "+" & s - a & ")"
End If
Next s
 
Sleep</syntaxhighlight>
{{out}}
<pre>17 (4+13)</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,005 ⟶ 1,325:
}
return pairs
}</langsyntaxhighlight>
{{out}}
For x + y < 100 (<code>max = 100</code>):
Line 1,028 ⟶ 1,348:
=={{header|Haskell}}==
{{trans|D}}
<langsyntaxhighlight lang="haskell">import Data.List (intersect)
 
s1, s2, s3, s4 :: [(Int, Int)]
Line 1,045 ⟶ 1,365:
s4 = filter (\p -> length (sumEq p `intersect` s3) == 1) s3
 
main = print s4</langsyntaxhighlight>
{{out}}
<pre>[(4,13)]</pre>
Line 1,057 ⟶ 1,377:
 
Finally, as we expect and need only one solution, Haskell's lazy evaluation strategy will avoid wasted tests if we request only the first item from the possible solution stream.
<langsyntaxhighlight Haskelllang="haskell">import Data.List (intersect)
 
------------------ SUM AND PRODUCT PUZZLE ----------------
 
s1, s2, s3, s4 :: [(Int, Int)]
s1 =
[2 .. 100] >>=
>>= \x ->
[succ x + 1 .. 100] >>=
>>= \y ->
[ (x, y)
| x + y < 100 ]
]
 
s2 = filter (all ((1 /=) . length . mulEq) . sumEq) s1
add, mul :: (Int, Int) -> Int
add = uncurry (+)
 
s3 = filter ((1 ==) . length . (`intersect` s2) . mulEq) s2
mul = uncurry (*)
 
s4 = filter ((1 ==) . length . (`intersect` s3) . sumEq) s3
 
sumEq, mulEq :: (Int, Int) -> [(Int, Int)]
sumEq p = filter ((add p ==) . add) s1
 
mulEq p = filter ((mul p ==) . mul) s1
 
add, mul :: (Int, Int) -> Int
s2 = filter (all ((1 /=) . length . mulEq) . sumEq) s1
add = uncurry (+)
mul = uncurry (*)
 
--------------------------- TEST -------------------------
s3 = filter ((1 ==) . length . (`intersect` s2) . mulEq) s2
 
s4 = filter ((1 ==) . length . (`intersect` s3) . sumEq) s3
 
-- TEST -----------------------------------------------------------------------
main :: IO ()
main = print $ take 1 s4</langsyntaxhighlight>
{{Out}}
<pre>[(4,13)]</pre>
 
=={{header|J}}==
'''Tacit Solution'''
<syntaxhighlight lang="j">(S=. X + Y) (P=. X * Y) (X=. 0&{"1) (Y=. 1&{"1)
(sd=. S </. ]) (pd=. P </. ]) NB. sum and product decompositions
 
candidates=. ([ echo o (' candidates' ,~ ": (o=. @:) #))
constraints=. (([ >: S o ]) and ((1 < X) and (1 < Y) (and=. *.) (X < Y)) o ])
filter0=. candidates o (constraints # ])
 
patesd=. S (< o P)/. ] NB. products associated to each sum decomposition
pmtod=. P o ; o (pd #~ 1 < P #/. ]) NB. products with more than one decomposition
filter1=. candidates o ((patesd ('' -: -.)&>"0 _ < o pmtod) ; o # sd)
 
filter2=. candidates o ; o (pd #~ 1 = (#&>) o pd)
filter3=. candidates o ; o (sd #~ 1 = (#&>) o sd)
 
decompositions=. > o , o { o (;~) o i.
show=. 'X=' , ": o X ,' Y=' , ": o Y , ' X+Y=' , ": o (X+Y) , ' X*Y=' , ": o (X*Y)
 
solve=. show :: (''"_) o filter3 o filter2 o filter1 o (] filter0 decompositions) f.
</syntaxhighlight>
 
Example use:
<syntaxhighlight lang="j"> solve 100
2352 candidates
145 candidates
86 candidates
1 candidates
X=4 Y=13 X+Y=17 X*Y=52
solve 64
930 candidates
62 candidates
46 candidates
0 candidates
 
solve 1685
707281 candidates
51011 candidates
17567 candidates
2 candidates
X=4 4 Y=13 61 X+Y=17 65 X*Y=52 244
solve 1970
967272 candidates
70475 candidates
23985 candidates
3 candidates
X=4 4 16 Y=13 61 73 X+Y=17 65 89 X*Y=52 244 1168
solve 2522
1586340 candidates
116238 candidates
37748 candidates
4 candidates
X=4 4 16 16 Y=13 61 73 111 X+Y=17 65 89 127 X*Y=52 244 1168 1776</syntaxhighlight>
 
The code is tacit and fixed (in other words, it is point-free):
<syntaxhighlight lang="j"> _80 [\ (5!:5)<'solve'
('X=' , ":@:(0&{"1) , ' Y=' , ":@:(1&{"1) , ' X+Y=' , ":@:(0&{"1 + 1&{"1) , ' X*
Y=' , ":@:(0&{"1 * 1&{"1)) ::(''"_)@:(([ 0 0&$@(1!:2&2)@:(' candidates' ,~ ":@:#
))@:;@:(((0&{"1 + 1&{"1) </. ]) #~ 1 = #&>@:((0&{"1 + 1&{"1) </. ])))@:(([ 0 0&$
@(1!:2&2)@:(' candidates' ,~ ":@:#))@:;@:(((0&{"1 * 1&{"1) </. ]) #~ 1 = #&>@:((
0&{"1 * 1&{"1) </. ])))@:(([ 0 0&$@(1!:2&2)@:(' candidates' ,~ ":@:#))@:((((0&{"
1 + 1&{"1) <@:(0&{"1 * 1&{"1)/. ]) ('' -: -.)&>"0 _ <@:((0&{"1 * 1&{"1)@:;@:(((0
&{"1 * 1&{"1) </. ]) #~ 1 < (0&{"1 * 1&{"1) #/. ]))) ;@:# (0&{"1 + 1&{"1) </. ])
)@:(] ([ 0 0&$@(1!:2&2)@:(' candidates' ,~ ":@:#))@:((([ >: (0&{"1 + 1&{"1)@:])
*. ((1 < 0&{"1) *. (1 < 1&{"1) *. 0&{"1 < 1&{"1)@:]) # ]) >@:,@:{@:(;~)@:i.)</syntaxhighlight>
 
=={{header|Java}}==
 
<langsyntaxhighlight Javalang="java">package org.rosettacode;
 
import java.util.ArrayList;
Line 1,239 ⟶ 1,630:
return list;
}
}</langsyntaxhighlight>
 
{{Out}}
Line 1,258 ⟶ 1,649:
 
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 1,353 ⟶ 1,744:
return s4;
})();
</syntaxhighlight>
</lang>
 
{{Out}}
<syntaxhighlight lang JavaScript="javascript">[[4, 13]]</langsyntaxhighlight>
(Finished in 0.69s)
 
Line 1,362 ⟶ 1,753:
===ES6===
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'"use strict'";
 
// ------------- SUM AND PRODUCT PUZZLE --------------
 
// main :: IO ()
const main = () => {
 
const
// xs :: [Int]
xs = enumFromTo(1, )(100),
 
// s1 s2, s3, s4 :: [(Int, Int)]
s1 = concatMapxs.flatMap(x => concatMap(y =>
((1 < x) &&=> xs.flatMap(x < y) && 100 => (x + y)) ? [
[(1 < x,) && (x < y]) && 100 > (x + y) ? [
] : []x, y]
xs), xs), ] : []
s2 = filter( )
),
p => all(q => 1 < length(mulEq(q, s1)), sumEq(p, s1)),
s2 = s1.filter(
p => sumEq(p, s1).every(
q => 1 < mulEq(q, s1).length
)
),
s3 = s2.filter(
p => 1 === length(intersectBy(pairEQ)(
pairEQ, mulEq(p, s1), s2
)(s2),.length
s2
);
 
return s3.filter(
p => 1 === length(intersectBy(pairEQ)(
pairEQ, sumEq(p, s1), s3
)(s3).length
);
};
 
// PROBLEM FUNCTIONS ------------------ PROBLEM FUNCTIONS ----------------
 
// add, mul :: (Int, Int) -> Int
Line 1,402 ⟶ 1,797:
mul = xy => xy[0] * xy[1],
 
// sumEq, mulEq :: (Int, Int) -> [(Int, Int)] -> [(Int, Int)]
// [(Int, Int)] -> [(Int, Int)]
sumEq = (p, s) => {
const addP = add(p);
 
return filter(q => add(q) === addP, s);
return s.filter(q => add(q) === addP);
},
mulEq = (p, s) => {
const mulP = mul(p);
 
return filter(q => mul(q) === mulP, s);
return s.filter(q => mul(q) === mulP);
},
 
// pairEQ :: ((a, a) -> (a, a)) -> Bool
pairEQ = (a, b) => (a[0]b === b[0]) &&> (a[1] === b[1]);
a[0] === b[0]
) && (a[1] === b[1]);
 
 
// GENERIC FUNCTIONS ------------------ GENERIC FUNCTIONS ----------------
 
// all :: (a -> Bool) -> [a] -> Bool
const all = (p, xs) => xs.every(p);
 
// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = (f, xs) =>
xs.reduce((a, x) => a.concat(f(x)), []);
 
// curry :: ((a, b) -> c) -> a -> b -> c
const curry = f => a => b => f(a, b);
 
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
 
// filter :: (a -> Bool) -> [a] -> [a]
const filter = (f, xs) => xs.filter(f);
 
// intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
const intersectBy = (eq, xs, ys)eqFn => {
const// ceqThe =intersection curry(eq);of the lists xs and ys
return// (0in <terms xs.lengthof &&the 0equality <defined ysby eq.length) ?
xs => ys => xs.filter(x => ys.some(ceq(x))) : [];
x => ys.some(eqFn(x))
};
);
 
// Returns Infinity over objects without finite length.
// This enables zip and zipWith to choose the shorter
// argument when one is non-finite, like cycle, repeat etc
 
// length :: [a] -> Int
const length = xs =>
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
 
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<syntaxhighlight lang JavaScript="javascript">[[4, 13]]</langsyntaxhighlight>
(Finished in 0.307s)
 
=={{header|jq}}==
Line 1,467 ⟶ 1,845:
 
A transcription from the problem statement, with these helper functions:
<syntaxhighlight lang="jq">
<lang jq>
# For readability:
def collect(c): map(select(c));
Line 1,510 ⟶ 1,888:
 
solve
</syntaxhighlight>
</lang>
{{out}}
<pre>[4,13]</pre>
Line 1,518 ⟶ 1,896:
using filters would be much slower in Julia, which often favors fast for loops over lists for speed.
 
<langsyntaxhighlight lang="julia">
using Primes
 
Line 1,561 ⟶ 1,939:
println("Solution: ($j, $(i - j))")
end
end</langsyntaxhighlight>
 
{{out}}
Line 1,567 ⟶ 1,945:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.4-3
 
data class P(val x: Int, val y: Int, val sum: Int, val prod: Int)
Line 1,587 ⟶ 1,965:
print("The only solution is : ")
for ((x, y, _, _) in fact3) println("x = $x, y = $y")
}</langsyntaxhighlight>
 
{{out}}
Line 1,596 ⟶ 1,974:
=={{header|Lua}}==
{{trans|C++}}
<langsyntaxhighlight lang="lua">function print_count(t)
local cnt = 0
for k,v in pairs(t) do
Line 1,738 ⟶ 2,116:
end
 
main()</langsyntaxhighlight>
{{out}}
<pre>2352 candidates
Line 1,745 ⟶ 2,123:
1 candidates
a=4, b=13; S=17, P=52</pre>
 
=={{header|MATLAB}}==
<syntaxhighlight lang="Matlab">
function SumProductPuzzle(maxSum, m)
% SumProductPuzzle(maxSum=100, m=2)
% Efficiently solve the Sum and Product puzzle.
% No solution if maxSum < 65; multiple solutions if maxSum >= 1685.
if nargin<2
m = 2; % minimum number
if nargin<1
maxSum = 100;
end
end
 
%Step 1: Determine viable sums; i.e. sums for which all possibilities have
% non-unique products
productCount = zeros(1,floor((maxSum/2)^2)); % Memory hog
for i = m:(maxSum/2-1)
j = i+1:maxSum-i;
ij = i*j;
productCount(ij) = productCount(ij) +1;
end
viableSum = true(1,maxSum);
viableSum(1:2*m) = false;
for s = 2*m+1:maxSum
i = m:(s-1)/2;
j = s-i;
if any(productCount(i.*j) == 1)
viableSum(s) = false;
end
end
tmp = 1:maxSum;
sums = tmp(viableSum);
N1 = sum(floor((sums+1)/2) - m);
fprintf( 1, 'After step 1: %d viable sums (%d total possibilities).\n', length(sums), N1 );
 
%Step 2: Determine which possibilities now have unique products
productCount = zeros(1,floor((maxSum/2)^2));
for s = sums
i = m:(s-1)/2;
j = s-i;
ij = i.*j;
productCount(ij) = productCount(ij) +1;
end
A = zeros(2,N1); %Pre-allocate for speed
n = 1;
for s = sums
i = m:(s-1)/2;
j = s-i;
ii = productCount(i.*j) == 1;
ij = [i(ii); j(ii)];
nn = n + size(ij,2);
A(:,n:nn-1) = ij;
n = nn;
end
A(:,nn:end) = [];
fprintf( 1, 'After step 2: %d possibilities.\n', size(A,2) );
 
%Step 3: Narrow down to pairs that have unique sums.
% Since the values are in sum order, just check the neighbor's sum.
d = diff(sum(A))==0;
ii = [d false] | [false d];
A(:,ii) = [];
 
switch size(A,2)
case 0
fprintf(1,'No solution.\n');
case 1
fprintf(1,'Puzzle solved! The numbers are %d and %d.\n', A(1:2));
otherwise
fprintf(1,'After step 3 there are still multiple possibilities:');
fprintf(1,' (%d, %d)', A(1:2,:));
fprintf(1,'\n');
end
</syntaxhighlight>
{{out}}
<pre>
>> tic; SumProductPuzzle; toc
After step 1: 10 viable sums (145 total possibilities).
After step 2: 86 possibilities.
Puzzle solved! The numbers are 4 and 13.
Elapsed time is 0.004797 seconds.
 
>> tic; SumProductPuzzle(1685); toc
After step 1: 235 viable sums (51011 total possibilities).
After step 2: 17567 possibilities.
After step 3 there are still multiple possibilities: (4, 13) (4, 61)
Elapsed time is 0.038874 seconds.
 
>> tic; SumProductPuzzle(1970); toc
After step 1: 278 viable sums (70475 total possibilities).
After step 2: 23985 possibilities.
After step 3 there are still multiple possibilities: (4, 13) (4, 61) (16, 73)
Elapsed time is 0.041495 seconds.
</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import sequtils, sets, sugar, tables
 
var
Line 1,794 ⟶ 2,267:
for s in sums:
for (x, y) in s.terms:
if x * y in factors: echo (x, y)</langsyntaxhighlight>
 
{{out}}
Line 1,803 ⟶ 2,276:
{{trans|REXX}}
for comments see REXX version 4.
<langsyntaxhighlight lang="oorexx">all =.set~new
Call time 'R'
cnt.=0
Line 1,892 ⟶ 2,365:
take=0
End
return epairs</langsyntaxhighlight>
{{out}}
<pre>There are 2352 pairs where X+Y <= MAX (and X<Y)
Line 1,902 ⟶ 2,375:
Uses objects for storing the number pairs. Note the computed hash value and the == method
(required to make the set difference work)
<langsyntaxhighlight lang="oorexx">all =.set~new
Call time 'R'
cnt.=0
Line 2,020 ⟶ 2,493:
::method string -- this creates the string to be shown
expose a b
return "[x="||a",y="||b"]"</langsyntaxhighlight>
{{out}}
<pre>There are 2352 pairs where X+Y <= MAX (and X<Y)
Line 2,030 ⟶ 2,503:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use List::Util qw(none);
 
sub grep_unique {
Line 2,068 ⟶ 2,541:
@final_pair = grep_unique(\&sum, @p_pairs);
 
printf "X = %d, Y = %d\n", split ' ', $final_pair[0];</langsyntaxhighlight>
{{out}}
<pre>X = 4, Y = 13</pre>
Line 2,075 ⟶ 2,548:
{{trans|AWK}}
Runs in 0.03s
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function satisfies_statement1(integer s)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
-- S says: P does not know the two numbers.
<span style="color: #008080;">function</span> <span style="color: #000000;">satisfies_statement1</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
-- Given s, for /all/ pairs (a,b), a+b=s, 2<=a,b<=99, at least one of a or b is composite
<span style="color: #000080;font-style:italic;">-- S says: P does not know the two numbers.
for a=2 to floor(s/2) do
-- Given s, for /all/ pairs (a,b), a+b=s, 2&lt;=a,b&lt;=99, at least one of a or b is composite</span>
if is_prime(a) and is_prime(s-a) then
<span style="color: #008080;">for</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
return 0
<span style="color: #008080;">if</span> <span style="color: #7060A8;">is_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">is_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">-</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
end if
<span style="color: #008080;">return</span> <span style="color: #004600;">false</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return 1
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #004600;">true</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function satisfies_statement2(integer p)
-- P says: Now I know the two numbers.
<span style="color: #008080;">function</span> <span style="color: #000000;">satisfies_statement2</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">)</span>
-- Given p, for /all/ pairs (a,b), a*b=p, 2<=a,b<=99, exactly one pair satisfies statement 1
<span style="color: #000080;font-style:italic;">-- P says: Now I know the two numbers.
integer winner = 0
-- Given p, for /all/ pairs (a,b), a*b=p, 2&lt;=a,b&lt;=99, exactly one pair satisfies statement 1</span>
for i=2 to floor(sqrt(p)) do
<span style="color: #004080;">bool</span> <span style="color: #000000;">winner</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
if mod(p,i)=0 then
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">))</span> <span style="color: #008080;">do</span>
integer j = floor(p/i)
<span style="color: #008080;">if</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
if 2<=j and j<=99 then
<span style="color: #004080;">integer</span> <span style="color: #000000;">j</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">/</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
if satisfies_statement1(i+j) then
<span style="color: #008080;">if</span> <span style="color: #000000;">2</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">j</span> <span style="color: #008080;">and</span> <span style="color: #000000;">j</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">99</span> <span style="color: #008080;">then</span>
if winner then return 0 end if
<span style="color: #008080;">if</span> <span style="color: #000000;">satisfies_statement1</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">j</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
winner = 1
<span style="color: #008080;">if</span> <span style="color: #000000;">winner</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">false</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #000000;">winner</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return winner
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">winner</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function satisfies_statement3(integer s)
-- S says: Now I know the two numbers.
<span style="color: #008080;">function</span> <span style="color: #000000;">satisfies_statement3</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
-- Given s, for /all/ pairs (a,b), a+b=s, 2<=a,b<=99, exactly one pair satisfies statements 1 and 2
<span style="color: #000080;font-style:italic;">-- S says: Now I know the two numbers.
integer winner = 0
-- Given s, for /all/ pairs (a,b), a+b=s, 2&lt;=a,b&lt;=99, exactly one pair satisfies statements 1 and 2</span>
if satisfies_statement1(s) then
<span style="color: #004080;">integer</span> <span style="color: #000000;">winner</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
for a=2 to floor(s/2) do
<span style="color: #008080;">if</span> <span style="color: #000000;">satisfies_statement1</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
if satisfies_statement2(a*(s-a)) then
<span style="color: #008080;">for</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if winner then return 0 end if
<span style="color: #008080;">if</span> <span style="color: #000000;">satisfies_statement2</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">-</span><span style="color: #000000;">a</span><span style="color: #0000FF;">))</span> <span style="color: #008080;">then</span>
winner = a
<span style="color: #008080;">if</span> <span style="color: #000000;">winner</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #000000;">winner</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">a</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return winner
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">winner</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
for s=2 to 100 do
integer a = satisfies_statement3(s)
<span style="color: #008080;">for</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">do</span>
if a!=0 then
<span style="color: #004080;">integer</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">satisfies_statement3</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
printf(1,"%d (%d+%d)\n",{s,a,s-a})
<span style="color: #008080;">if</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
end if
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d (%d+%d)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">-</span><span style="color: #000000;">a</span><span style="color: #0000FF;">})</span>
end for</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
17 (4+13)
</pre>
=={{header|Picat}}==
<syntaxhighlight lang="picat">
main =>
N = 98,
PD = new_array(N*N), % PD[I] = no. of product decompositions of I
foreach(I in 1..N*N) PD[I] = 0 end,
foreach(X in 2..N-1, Y in X+1..N) PD[X * Y] := PD[X * Y] + 1 end,
 
% Fact 1: S says "P does not know X and Y.", i.e.
% For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition:
Solutions1 = [[X,Y] : X in 2..N-1, Y in X+1..100-X, foreach(XX in 2..X+Y-3) PD[XX * (X+Y-XX)] > 1 end],
 
% Fact 2: P says "Now I know X and Y.", i.e.
% The number X*Y has only one product decomposition for which fact 1 is true:
Solutions2 = [[X,Y] : [X,Y] in Solutions1, foreach([XX,YY] in Solutions1, XX * YY = X * Y) XX = X, YY = Y end],
 
% Fact 3: S says "Now I also know X and Y.", i.e.
% The number X+Y has only one sum decomposition for which fact 2 is true.
Solutions3 = [[X,Y] : [X,Y] in Solutions2, foreach([XX,YY] in Solutions2, XX + YY = X + Y) XX = X, YY = Y end],
 
println(Solutions3).
</syntaxhighlight>
Output:
<pre>[[4,13]]</pre>
 
=={{header|Python}}==
 
Based on the Python solution from [[wp:Sum_and_Product_Puzzle#Python_code|Wikipedia]]:
<langsyntaxhighlight lang="python">#!/usr/bin/env python
 
from collections import Counter
Line 2,157 ⟶ 2,657:
final_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]
 
print(final_pairs)</langsyntaxhighlight>
 
{{out}}
Line 2,164 ⟶ 2,664:
=={{header|Racket}}==
{{trans|D}}To calculate the results faster this program use memorization. So it has a modified version of <code>sum=</code> and <code>mul=</code> to increase the chances of reusing the results.
<langsyntaxhighlight Racketlang="racket">#lang racket
(define-syntax-rule (define/mem (name args ...) body ...)
(begin
Line 2,204 ⟶ 2,704:
(displayln s4))
 
(puzzle 100)</langsyntaxhighlight>
{{out}}
<pre>Max Sum: 100
Line 2,217 ⟶ 2,717:
{{trans|Python}}
{{works with|Rakudo|2016.07}}
<syntaxhighlight lang="raku" perl6line>sub grep-unique (&by, @list) { @list.classify(&by).values.grep(* == 1).map(*[0]) }
sub sums ($n) { ($_, $n - $_ for 2 .. $n div 2) }
sub sum ([$x, $y]) { $x + $y }
sub product ([$x, $y]) { $x * $y }
sub sum ([$x, $y]) { $x + $y }
 
my @all-pairs = (|($_ X $_+1 .. 98) for 2..97);
Line 2,234 ⟶ 2,734:
my @final-pairs = grep-unique &sum, @p-pairs;
 
printf "X = %d, Y = %d\n", |$_ for @final-pairs;</langsyntaxhighlight>
 
{{out}}
Line 2,247 ⟶ 2,747:
http://www.win.tue.nl/~gwoegi/papers/freudenthal1.pdf
which had a very clear description.
<langsyntaxhighlight lang="rexx">debug=0
If debug Then Do
oid='sppn.txt'; 'erase' oid
Line 2,473 ⟶ 2,973:
End
/* Say swl */
Return strip(swl)</langsyntaxhighlight>
{{out}}
<pre>2352 possible pairs
Line 2,486 ⟶ 2,986:
===version 2===
{{trans|AWK}}
<langsyntaxhighlight lang="rexx">Call time 'R'
Do s=2 To 100
a=satisfies_statement3(s)
Line 2,545 ⟶ 3,045:
If datatype(x/i,'W') Then Return 0
End
Return 1</langsyntaxhighlight>
{{out}}
<pre>4/13 s=17 p=52
Line 2,552 ⟶ 3,052:
===version 3===
{{trans|GO}}
<langsyntaxhighlight lang="rexx">/*---------------------------------------------------------------------
* X and Y are two different whole numbers greater than 1.
* Their sum is no greater than 100, and Y is greater than X.
Line 2,660 ⟶ 3,160:
End
Say "Elapsed time:" time('E') "seconds"
Exit</langsyntaxhighlight>
{{out}}
<pre>There are 2352 pairs where X+Y <= 100 (and X<Y)
Line 2,670 ⟶ 3,170:
===version 4===
Now that I have understood the logic (I am neither S nor P) I have created an alternative to version 3.
<langsyntaxhighlight lang="rexx">/*---------------------------------------------------------------------
* X and Y are two different whole numbers greater than 1.
* Their sum is no greater than 100, and Y is greater than X.
Line 2,781 ⟶ 3,281:
End
Say "Elapsed time:" time('E') "seconds"
Exit</langsyntaxhighlight>
{{out}}
<pre>There are 2352 pairs where X+Y <= 100 (and X<Y)
Line 2,791 ⟶ 3,291:
===version 5, fast ===
This REXX version is over &nbsp; '''ten''' &nbsp; times faster than the previous REXX version.
<langsyntaxhighlight lang="rexx">/*REXX program solves the Sum and Product Puzzle (also known as the Impossible Puzzle).*/
@.= 0; h= 100; @.3= 1 /*assign array default; assign high P.*/
do j=5 by 2 to h /*find all odd primes ≤ 1st argument.*/
Line 2,817 ⟶ 3,317:
else $= 1
end
end /*j*/; return $</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default internal input:}}
<pre>
Line 2,825 ⟶ 3,325:
=={{header|Ruby}}==
{{trans|D}}
<langsyntaxhighlight lang="ruby">def add(x,y) x + y end
def mul(x,y) x * y end
 
Line 2,834 ⟶ 3,334:
s2 = s1.select{|p| sumEq(s1,p).all?{|q| mulEq(s1,q).size != 1} }
s3 = s2.select{|p| (mulEq(s1,p) & s2).size == 1}
p s3.select{|p| (sumEq(s1,p) & s3).size == 1}</langsyntaxhighlight>
 
{{out}}
<pre>
[[4, 13]]
</pre>
 
=={{header|Rust}}==
{{trans|Julia}}
<syntaxhighlight lang="rust">use primes::is_prime;
 
fn satisfy1(x: u64) -> bool {
let upper_limit = (x as f64).sqrt() as u64 + 1;
for i in 2..upper_limit {
if is_prime(i) && is_prime(x - i) {
return false;
}
}
return true;
}
 
fn satisfy2(x: u64) -> bool {
let mut once: bool = false;
let upper_limit = (x as f64).sqrt() as u64 + 1;
for i in 2..upper_limit {
if x % i == 0 {
let j = x / i;
if 2 < j && j < 100 && satisfy1(i + j) {
if once {
return false;
}
once = true;
}
}
}
return once
}
 
fn satisfyboth(x: u64) -> u64 {
if !satisfy1(x) {
return 0;
}
let mut found = 0;
for i in 2..=(x/2) {
if satisfy2(i * (x - i)) {
if found > 0 {
return 0;
}
found = i;
}
}
return found;
}
 
fn main() {
for i in 2..100 {
let j = satisfyboth(i);
if j > 0 {
println!("Solution: ({}, {})", j, i - j);
}
}
}
</syntaxhighlight>{{out}}
<pre>
Solution: (4, 13)
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object ImpossiblePuzzle extends App {
type XY = (Int, Int)
val step0 = for {
Line 2,859 ⟶ 3,419:
val step4 = step3 filter { sumEq(_).intersect(step3).size == 1 }
println(step4)
}</langsyntaxhighlight>
{{out}}
<pre>Vector((4,13))</pre>
Line 2,866 ⟶ 3,426:
=={{header|Scheme}}==
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme cxr)
Line 2,917 ⟶ 3,477:
(number->string (cadar *fact-3*))
"\n"))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,930 ⟶ 3,490:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func grep_uniq(a, by) { a.group_by{ .(by) }.values.grep{.len == 1}.map{_[0]} }
func sums (n) { 2 .. n//2 -> map {|i| [i, n-i] } }
 
Line 2,942 ⟶ 3,502:
var f_pairs = grep_uniq(p_pairs, :sum)
 
f_pairs.each { |p| printf("X = %d, Y = %d\n", p...) }</langsyntaxhighlight>
{{out}}
<pre>
Line 2,952 ⟶ 3,512:
{{libheader|Wren-dynamic}}
{{libheader|Wren-seq}}
<langsyntaxhighlight ecmascriptlang="wren">import "./dynamic" for Tuple
import "./seq" for Lst
 
var P = Tuple.create("P", ["x", "y", "sum", "prod"])
Line 2,986 ⟶ 3,546:
var fact3 = fact2.where { |c| intersect.call(sumMap[c.sum], fact2).count == 1 }.toList
System.write("The only solution is : ")
for (p in fact3) System.print("x = %(p.x), y = %(p.y)")</langsyntaxhighlight>
 
{{out}}
Line 2,995 ⟶ 3,555:
=={{header|zkl}}==
Damn it Jim, I'm a programmer, not a logician. So I translated the python code found in https://qmaurmann.wordpress.com/2013/08/10/sam-and-polly-and-python/ but I don't understand it. It does seem quite a bit more efficient than the Scala code, on par with the Python code.
<langsyntaxhighlight lang="zkl">mul:=Utils.Helpers.summer.fp1('*,1); //-->list.reduce('*,1), multiply list items
var allPairs=[[(a,b); [2..100]; { [a+1..100] },{ a+b<100 }; ROList]]; // 2,304 pairs
 
Line 3,005 ⟶ 3,565:
sOK2:='wrap(s){ 1==sxys[s].filter('wrap(xy){ pOK(xy:mul(_)) }).len() };
allPairs.filter('wrap([(x,y)]){ sOK(x+y) and pOK(x*y) and sOK2(x+y) })
.println();</langsyntaxhighlight>
[[ ]] denotes list comprehension, filter1 returns (and stops at) the first thing that is "true", 'wrap creates a closure so the "wrapped" code/function can see local variables (read only). In a [function] prototype, the "[(x,y)]xy]" notation says xy is a list like thing, assign the parts to x & y (xy is optional), used here to just to do it both ways. The ":" says take the LHS and stuff it into the "_".
{{out}}<pre>L(L(4,13))</pre>
2,122

edits