Sum and product puzzle: Difference between revisions
Content added Content deleted
Walterpachl (talk | contribs) m (→{{header|REXX}}: added wordsort as internal procedure) |
m (→version 5, fast: simplified some code, split a long line, optimized search.) |
||
Line 2,754: | Line 2,754: | ||
===version 5, fast === |
===version 5, fast === |
||
This REXX version is over '''ten''' times faster than the previous REXX version. |
|||
<lang rexx>/*REXX program solves the Sum and Product Puzzle (also known as the Impossible Puzzle).*/ |
<lang rexx>/*REXX program solves the Sum and Product Puzzle (also known as the Impossible Puzzle).*/ |
||
@.=0; |
@.= 0; H= 100; @.3= 1 /*assign array default; assign high P.*/ |
||
do j=5 by 2 to H /*find all odd primes ≤ 1st argument.*/ |
|||
do k=3 while k*k<=j; if j//k==0 then iterate j /*J ÷ by K ? */ |
|||
end /* |
end /*k*/; @.j= 1 /*found a prime number: J */ |
||
end /*j*/ |
|||
@.2=1 /*assign the even prime, ex post facto.*/ |
@.2=1 /*assign the even prime, ex post facto.*/ |
||
do s=2 for H-1; if C1(s)==0 then iterate /*find and display the puzzle solution.*/ |
do s=2 for H-1; if C1(s)==0 then iterate /*find and display the puzzle solution.*/ |
||
Line 2,766: | Line 2,768: | ||
if $>0 then say "The numbers are: " $ " and " s-$ |
if $>0 then say "The numbers are: " $ " and " s-$ |
||
end /*s*/ |
end /*s*/ |
||
exit |
exit 0 /*stick a fork in it, we're all done. */ |
||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
C1: procedure expose @.; |
C1: procedure expose @.; parse arg s /*validate the first puzzle condition. */ |
||
do a=2 for s%2-1; if @.a then do; _=s-a; if @._ then return 0; |
do a=2 for s%2-1; if @.a then do; _= s - a; if @._ then return 0; end |
||
end; /*a*/; return 1 |
|||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
C2: procedure expose @. H; parse arg p; $= 0 /*validate the second puzzle condition.*/ |
C2: procedure expose @. H; parse arg p; $= 0 /*validate the second puzzle condition.*/ |
||
do j=2 while j*j |
do j=2 while j*j<p /*perform up to the square root of P. */ |
||
if p//j==0 then do; q= p % j |
if p//j==0 then do; q= p % j |
||
if q>=2 then if q<=H then if C1(j+q) then if $ then return 0 |
if q>=2 then if q<=H then if C1(j+q) then if $ then return 0 |