Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate sum of two squares

Tags:

algorithm

I'm looking for an efficient way to iterate over the infinite non-decreasing sequence defined by a^2+b^2 where a, b are both positive integers. What I mean by iterate here, is that given an existing list of n entries, the algorithm should efficiently (I'm hoping for O(log(m)), where m=a^2+b^2) find the next entry.

The start of this list is: 1^2+1^2=2, 1^2+2^2=5, 2^2+2^2=8, 1^2+3^2=10, 2^2+3^2=13, 1^2+4^2=17, ...

Here's the python code used to generate these entries (the first 100 are correct):

xs=[]
for i in range(1, 100):
    for j in range(i, 100):
        xs.append((i**2+j**2, i, j))
xs.sort()

I've looked at the start of the list and can't see any pattern at all. Anyone know an algorithm to do this?

[edit] Upon some searching, I found Cornacchia's algorithm which requires computing a quadratic residue. However I'm still hoping for something better, as we already know the previous numbers during iteration.

like image 704
simonzack Avatar asked Nov 21 '13 11:11

simonzack


People also ask

Which squares are the sum of two squares?

Given any integer, you can tell whether it can be written as the sum of two squares if you find its prime factorization. If all of the primes that are one less than multiples of four have even exponents in the prime factorization of your number, then it can be written as the sum of two squares.

How do you find the sum of squares in Python?

FAQs Related to the Sum of Squares in Python(N*(N +1)*(2*N+1))/6 is the formula to calculate the sum of squares of n natural numbers.

Which of the following can be expressed as sum of two squares?

All prime numbers which are sums of two squares, except 2, form this series: 5, 13, 17, 29, 37, 41, 53, 61, 73, 89, 97, 101, 109, 113, 137, 149, etc. Not only are these contained in the form 4n + 1, but also, however far the series is continued, we find that every prime number of the form 4n+1 occurs.


1 Answers

The isSumOfSquares function returns True if n can be written as a sum of squares greater than zero and False otherwise, based on an algorithm from Edsgar Dijkstra's 1976 book The Discipline of Programming: x sweeps downward from the square root of n, decreasing when the sum of the squares is too large, and y sweeps upward from 1, increasing when the sum of the squares is too small.

from math import sqrt

def isSumOfSquares(n):
    x, y = int(sqrt(n)), 1
    while x >= y:
        if x*x + y*y < n: y = y + 1
        elif x*x + y*y > n: x = x - 1
        else: return True
    return False

filter(isSumOfSquares, range(1,100))

This returns the list [2, 5, 8, 10, 13, 17, 18, 20, 25, 26, 29, 32, 34, 37, 40, 41, 45, 50, 52, 53, 58, 61, 65, 68, 72, 73, 74, 80, 82, 85, 89, 90, 97, 98]. I discussed a similar question at my blog.

like image 114
user448810 Avatar answered Sep 21 '22 08:09

user448810