Home > Back-end >  I need to optimaze my code that containt two loops. The code is for calculating a sum of numbers
I need to optimaze my code that containt two loops. The code is for calculating a sum of numbers

Time:11-01

I was traying to write a code that calculate the sum of 2*j i 1 where 0<=j<=i<=n but I wasn't very optimazed there are my code :

def get_sum(n):
    s=0
    for j in range(n 1):
        ss=0
        ss=sum(2*j i 1 for i in range(j,n 1))
        s =ss
    return s

Write to calculate a a sum of 2*j i 1 where 0<=j<=i<=n but it wasn't optimazed

CodePudding user response:

Before delving into optimizing the code, always take a step back and consider what the code does. In this case, try to solve the equations with pen and paper, instead of brute-forcing them with a computer.

The value you want, lets call it S is defined as

enter image description here

Compute the inner sum first

enter image description here

And, finally, substitute and compute the outer sum

enter image description here

The second to last expression is the fastest one to use, as it uses fewer multiplications (and an "easier" division). If you are unfamiliar with any of the math above, look up the basic summation properties and identities.

And your function is simply

def get_sum(n):
    return (n 1)*(n 2)*(4*n 3)/2

CodePudding user response:

This is really just a math question:

def get_sum2(n):
    return (4*n*n*n   15*n*n   17*n   6)/6

As you mentioned that you want to simplify the code:

sum([2*j i 1 for i in range(n 1) for j in range(i 1)])
  • Related