# Python function to find all integers between two numbers whose sum of squared divisors is a perfect square

Divisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42. These divisors squared are: 1, 4, 9, 36, 49, 196, 441, 1764. The sum of the squared divisors is 2500 which is 50 * 50, a square!

Given two integers m, n (1 <= m <= n) we want to find all integers between m and n whose sum of squared divisors is itself a square. 42 is such a number.

The result will be an array of arrays, each subarray having two elements, first the number whose squared divisors is a square and then the sum of the squared divisors.

I have a working function as follows, however it does not execute fast enough.

from math import sqrt
def list_squared(m, n):
def D(x):return sum(i**2 for i in range(1,x+1) if not x%i)
return [[i,D(i)] for i in range(m,n) if sqrt(D(i)).is_integer()]


I have also tried a for loop instead of list comprehension, using a variable to save the output of the D function so it doesn't get called twice, and it didn't help. I have no experience optimizing code for speed.

from math import sqrt
def list_squared(m, n):
def D(x):return sum(i**2 for i in range(1,x+1) if not x%i)
z = []
for i in range(m,n):
x = D(i)
if sqrt(x).is_integer():
z.append([i,x])
return z


#Examples
list_squared(1, 250) --> [[1, 1], [42, 2500], [246, 84100]]
list_squared(42, 250) --> [[42, 2500], [246, 84100]]

• "however it does not execute fast enough" - is a time limit exceeded? you could add the tag time-limit-exceeded – Sᴀᴍ Onᴇᴌᴀ May 17 '18 at 18:52
• Yes, a time limit is exceeded on the executing server, however it does not state what that limit is, only that I surpassed it and to optimize my code more. – Cyber17C May 17 '18 at 18:56

def D(x):