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]]