Project Euler #211: Divisor Square Sum

  • + 0 comments

    please help in reducing complexity

    or feel free to give any advice

    import math
    
    def sum_square_divisor(x):
        sum_num=0
        for i in range(1,int(math.sqrt(x))+1):
            if(x%i==0):
                if(x/i==i):
                    sum_num+=i*i
                else:
                    sum_num+=i*i
                    sum_num+=int((x/i))*int((x/i))
        return sum_num
    
    def isaperfectsquare(x):
        sr=math.sqrt(x)
        return ((sr-math.floor(sr))==0)
    
    q = int(input())
    for i in range(q):
        arr=list(map(int, input().split()))
        N=arr[0]
        K=arr[1]
        check_list=[]
        finalsum=0
        for n in range(1,N+1):
            if(n==1):
                for j in range(K+1):
                    check_pos=n+j
                    check_neg=n-j
                    if(check_neg>0):
                        if(isaperfectsquare(check_pos) or isaperfectsquare(check_neg)):
                            finalsum+=n
                            break
                    else:
                        if(isaperfectsquare(check_pos)):
                            finalsum+=n
                            break
                
            else:
                divisor_sum=sum_square_divisor(n)
                for j in range(K+1):
                    check_pos=divisor_sum+j
                    check_neg=divisor_sum-j
                    if(check_neg>0):
                        if(isaperfectsquare(check_pos) or isaperfectsquare(check_neg)):
                            finalsum+=n
                            break
                    else:
                        if(isaperfectsquare(check_pos)):
                            finalsum+=n
                            break
       
        print(finalsum)