Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>My idea:</p> <ul> <li>Generate all squares between 0 and 2147483647</li> <li>For each X: <ul> <li>count = 0</li> <li>Have 2 iterators - one starting from the left and one starting from the right</li> <li>If <code>left + right = X</code>, increase the count, increase the left iterator and decrease the right one</li> <li>If <code>left + right &gt; X</code>, decrease the right one</li> <li>If <code>left + right &lt; X</code>, increase the left one</li> <li>Stop when <code>left</code> bypasses <code>right</code> </li> </ul></li> </ul> <p>As an optimization, we don't need to start all the way on the right, we can instead do a binary search for the starting position.</p> <p>Test code:</p> <pre><code>private static int binarySearch(long[] a, long key) { int low = 0; int high = a.length - 1; while (low &lt;= high) { int mid = (low + high) &gt;&gt;&gt; 1; long midVal = a[mid]; if (midVal &lt; key) low = mid + 1; else if (midVal &gt; key) high = mid - 1; else return mid; } return Math.min(low, a.length-1); } public static void main(String[] args) { long[] squares = new long[46341]; // ceil(sqrt(2147483647)) = 46341 long val = 0; int pos = 0; while (true) { long square = val*val; // sanity check, can also use pos &gt;= squares.length if (square &gt; 2147483647l) break; squares[pos++] = square; val++; } int X = 10; int left = 0; int right = binarySearch(squares, X); int count = 0; for (; left &lt;= right; ) { //Collections.b long l = squares[left] + squares[right]; if (l == X) { count++; left++; right--; } else if (l &gt; X) { right--; } else { left++; } } System.out.println(count); } </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. This table or related slice is empty.
    1. 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