Pythagorean Quadruple
February 25, 2020
(define (pyquad n) (list-of (list a b c d) (a range 1 (+ n 1)) (b range a (+ n 1)) (c range b (+ n 1)) (s is (+ (* a a) (* b b) (* c c))) (d is (isqrt s)) (= (* d d) s)))
That finds the 85490 Pythagorean quadruples less than 1000 in a little bit less than a minute and a half on my machine.
The time complexity of that function is clearly O(n³) due to the three nested loops on a, b and c. It seems to me that there ought to be an O(n²) solution by first computing a² + b² in O(n²) time, storing each of the (a b) pairs keyed by the sum of its squares, and comparing to d² – c², but I couldn’t find an appropriate method to limit c and d.
You can run the program at https://ideone.com/m3D0yF.
Interesting problem. Here is my take on it using Julia: https://pastebin.com/eYYR51sm
For N = 1000 I found 85490 quadruples (allowing for multiple instances of the same number in the quadruple set).
Cheers
Here’s a C++ solution that runs in O(n²) time, using O(n²) space (assuming hash table access time is constant):
Just in case overflow in all those squares is a problem, I thought I’d see what gcc can do to check things at runtime:
Here’s a slightly improved version (that prints spaces between the values for a,b,c,d):
Here’s a solution in Python.
Output: