Python - Fastest way to find all perfect squares in a given large number range

Vrashabh Irde picture Vrashabh Irde · Apr 13, 2013 · Viewed 8.3k times · Source

I am trying to write a method to get all the perfect squares in a given range in Python. A large range like between 2621163 and 520001400002. Now obviously iterating through the range and checking if a number is perfect like so

def is_square(n):
    return math.sqrt(n).is_integer()

and then printing it is stupid for large ranges (works great for small ranges) and will take forever. I am wondering if there is any Python magic or mathemagic (say a modified Diophantine equation) that I can leverage for this purpose.

EDIT: Also I am using Python 3.X so I can use large integers.

Answer

grc picture grc · Apr 13, 2013

You can simply find the smallest and largest numbers that have squares in the specified range. Then you can return the squares of every number in that range.

import math

def perfect_squares(min, max):
    lowest = int(math.ceil(math.sqrt(min)))
    highest = int(math.sqrt(max))
    return (n**2 for n in range(lowest, highest + 1))