Home > Enterprise >  Program to compute sum of squares function
Program to compute sum of squares function

Time:02-13

I wish to write a program to compute the Sum of squares function in python with k <= 6 and n < 2500. I thought that a possible approach could be to create an array of perfect squares and split the number into perfect squares from the array and then go about changing the signs and counting the representations. But I am struggling to do this as I am finding it hard to split the number based on the numbers in the array. Any help as to how I could compute r_{k}(n) would be much appreciated.

CodePudding user response:

Check this snippet

def sum_of_squares(n, k):
    perfect_squares = []
    temp = n
    combinations = []
    for i in range(1,n 1):
        if i**2 <= n :
            perfect_squares.append( (i,i**2) )
    perfect_squares = perfect_squares[::-1]
    
    while temp > 0:
        if perfect_squares == []:
            break
        
        if perfect_squares[0][1] <= temp:
            temp = temp - perfect_squares[0][1]
            combinations.append( (perfect_squares[0][0], 2) )
        else:
            perfect_squares = perfect_squares[1:]
    
    if len(combinations) <= k:
        for i in range(k-len(combinations)):
            combinations.append((0,2))
    else:
        return False

    return sum( [ i[1] for i in combinations ] )
    
print(sum_of_squares(n=2,k=2))

you can print the combinations to see the squares.

CodePudding user response:

try this

def sum_squares():

    squares = []
    for i in range(6, 2500):
        squares.append(i**2)
    return sum(squares)
  • Related