-2

I'm trying to optimize this code (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). I'm new to coding and I'm having a hard time with this concept

  def list_squared(m, n):
    # your code
     import math
     MyList = []
     for i in range(m,n):
         A=[]
         for k in range(1,i+1):
             if i%k == 0:
                A.append(k**2)
         if round(math.sqrt(sum(A))) == math.sqrt(sum(A)):
                  B =[]
                  B.append(i)
                  B.append(sum(A))
                 MyList.append(B)
      return MyList
idjaw
  • 25,487
  • 7
  • 64
  • 83
  • 2
    Welcome to your first question on StackOverflow. However, this site is not for broad optimization questions. Perhaps you should try [Code Review](https://codereview.stackexchange.com/). But be sure to read their tour and follow their quality standards. – Rory Daulton Jul 09 '17 at 18:08
  • 2
    Possible duplicate of [How could I check if a number is a perfect square?](https://stackoverflow.com/questions/2489435/how-could-i-check-if-a-number-is-a-perfect-square) – Harshith Thota Jul 09 '17 at 18:26

2 Answers2

0
import math
def list_squared(m, n):
     MyList = []
     for i in range(m,n):
         res=0
         for k in range(1,i+1):
             if i%k == 0:
                res+=k**2
         if res == int(math.sqrt(res))**2
                 MyList.append(i)
      return MyList
Harshith Thota
  • 856
  • 8
  • 20
0

First thing that i note you can optimize is range(1,i+1). You can set initially res=1 and start the range from 2 avoiding the first cycle. The important optimization is in the end: you can stop after i/2 because there are not integer divisors after it but remember to include the dispair case (for example 3/2 = 1.5 is not a valid input for range) so wrap the result of division around ceil function. In conclusion a simple optimization is range(2, ceil(i/2)+1) with res=1

Mikedev
  • 316
  • 1
  • 8