Jump to content

Sum and product puzzle: Difference between revisions

m
→‎version 5, fast: simplified some code, split a long line, optimized search.
m (→‎{{header|REXX}}: added wordsort as internal procedure)
m (→‎version 5, fast: simplified some code, split a long line, optimized search.)
Line 2,754:
 
===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).*/
@.= 0; H=100; do j=3 by 2 to H H= 100; /*find@.3= all1 odd primes /*assign array default; assign 1sthigh argumentP.*/
do j=5 by 2 to H do k=3 until k*k>j; if @.k==0 then iterate; if j//k==0*find all thenodd iterateprimes j ≤ 1st argument.*/
do k=3 end while /k*k*/<=j; if j//k==0 then iterate j @.j= 1 /*found a prime number: J ÷ by K ? */
end /*k*/; @.j= 1 /*jfound a prime number: J */
end /*j*/
@.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.*/
Line 2,766 ⟶ 2,768:
if $>0 then say "The numbers are: " $ " and " s-$
end /*s*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
C1: procedure expose @.; parse arg s 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; end; end; return 1
end; /*a*/; return 1
/*──────────────────────────────────────────────────────────────────────────────────────*/
C2: procedure expose @. H; parse arg p; $= 0 /*validate the second puzzle condition.*/
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 q>=2 then if q<=H then if C1(j+q) then if $ then return 0
Cookies help us deliver our services. By using our services, you agree to our use of cookies.