Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This problem was discussed by Edsgar Dijkstra in his 1976 book <em>The Discipline of Programming</em>. Dijkstra finds all pairs in a single pass as <em>x</em> sweeps downward from the integer square root of <em>n</em> and <em>y</em> sweeps upward from zero. Consider the function <code>B(x, y)</code> that returns all suitable pairs between <em>x</em> and <em>y</em>, guided by the following three recursive rules plus a recursive base:</p> <ul> <li>If x² + y² &lt; n, then B(x, y) = B(x, y+1), because there is no possible solution (u, v) with x ≥ u, since that would imply u² + v² &lt; n.</li> <li>If x² + y² = n, then the pair (x, y) is a solution, B(x, y) = (x, y) &Union; B(x-1, y+1), and the sweep continues.</li> <li>If x² + y² > n, then B(x, y) = B(x-1, y), because there is no possible solution with any x.</li> <li>Finally, if x &lt; y, B(x, y) is the null set, and recursion stops.</li> </ul> <p>Here's how I wrote the solution in Scheme at <a href="http://programmingpraxis.com/2010/01/05/the-sum-of-two-squares/" rel="nofollow">my blog</a>; I'll leave it to you to translate to Java:</p> <pre><code>(define (squares n) (let loop ((x (isqrt n)) (y 0) (zs '())) (cond ((&lt; x y) zs) ((&lt; (+ (* x x) (* y y)) n) (loop x (+ y 1) zs)) ((&lt; n (+ (* x x) (* y y))) (loop (- x 1) y zs)) (else (loop (- x 1) (+ y 1) (cons (list x y) zs)))))) </code></pre> <p>And here are some examples, which you may find useful as test cases:</p> <pre><code>&gt; (squares 50) ((5 5) (7 1)) &gt; (squares 48612265) ((5008 4851) (5139 4712) (5179 4668) (5243 4596) (5432 4371) (5613 4136) (5656 4077) (5691 4028) (5832 3821) (5907 3704) (6048 3469) (6124 3333) (6213 3164) (6259 3072) (6384 2803) (6404 2757) (6413 2736) (6556 2373) (6576 2317) (6637 2136) (6651 2092) (6756 1723) (6772 1659) (6789 1588) (6853 1284) (6899 1008) (6917 876) (6944 627) (6948 581) (6952 531) (6971 132) (6972 59)) &gt; (squares 999) () </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload