Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I like sequences, but in this case, they are probably the wrong tool for the job. This problem is a chance to try out a non-trivial recursive solution. Using mutation, it would be easy to do an algorithm like this (in Python, my pseudo-code of choice..)</p> <pre><code>def f(n): i = 0 j = int(1 + sqrt(n)) count = 0 # 'i' will always be increased, and j will always be decreased. We # will stop if i &gt; j, so we can avoid duplicate pairs. while i &lt;= j: s = i * i + j * j if s &lt; n: # if any answers exist for this i, they were with higher # j values. So, increment i. i += 1 elif s &gt; n: # likewise, if there was an answer with this j, it was # found with a smaller i. so, decrement it. j -= 1 else: # found a solution. Count it, and then move both i and # j, because they will be found in at most one solution pair. count += 1 i += 1 j -= 1 return count </code></pre> <p>Now, this seems to work. Maybe its not right, or not the best, but I like how the recursive code looks in F#. (warning.. I don't have F# on this computer... but I hope I got this right.)</p> <pre><code>let f n = let rec go i j count = if i &gt; j then count else let s = i * i + j * j if s &lt; n then go (i + 1) j count else if s &gt; n then go i (j - 1) count else go (i + 1) (j - 1) (count + 1) go 0 (1 + (n |&gt; float |&gt; sqrt |&gt; int)) 0 </code></pre> <p>This solution runs in O(sqrt(N)) time for each call, and requires constant memory. The memoizing solution takes O(N) time to setup the dictionary and the dictionary size is at least O(sqrt(N)). For large N, these are quite different. </p>
    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