Reputation:
I was trying figure out if there is a more efficient way to code it but i couldn't. Could anyone please help me to figure out if there is a more efficient way to code it?
So here is the code:
def iterative(n):
sum = 0
for i in range(1,n+1):
form = i*(i+1)**2
sum = sum + form
return(sum)
Thanks in advance!
Upvotes: 1
Views: 67
Reputation: 92461
If you are truly looking for speed, you could just do the math and remove the iterative aspect from it. Sums of polynomials can be broken into sums of sums and those small sums can be solved directly with something like this (just be careful of float precision if the number will be huge):
def iterative4(n):
return (n * (n + 1)//2)**2 + (n * (n + 1) * (2 * n + 1))//3 + (n * (n + 1))//2
Here for example, it is several orders of magnitude faster — you could calculate the value with n = 10000000 roughly 15000 times in the time it takes the iterative approach to do it once:
def iterative1(n):
return sum(i * (i + 1) ** 2 for i in range(1, n + 1))
def iterative4(n):
return (n * (n + 1)//2)**2 + (n * (n + 1) * (2 * n + 1))//3 + (n * (n + 1))//2
x = time.time()
print(iterative4(10000000))
print(time.time() - x)
#2500001166666841666675000000
#0.00030493736267089844
x = time.time()
print(iterative1(10000000))
print(time.time() - x)
#2500001166666841666675000000
#4.789726972579956
Upvotes: 1
Reputation: 1927
If you mean shorter, then:
def iterative(n):
return sum(i * (i + 1) ** 2 for i in range(1, n + 1))
print(iterative(10))
made some efficiency testing with all the answers here:
def iterative1(n):
return sum(i * (i + 1) ** 2 for i in range(1, n + 1))
def iterative2(n):
sum = 0
for i in range(1, n + 1):
form = i * (i + 1) ** 2
sum = sum + form
return (sum)
def iterative3(n):
return sum(map(lambda i: i*(i+1)**2, range(1,n+1)))
import time
x = time.time()
print(iterative1(10000000))
print( time.time() - x) # 5.313434600830078
x = time.time()
print(iterative2(10000000))
print(time.time() - x) # 5.021821975708008
x = time.time()
print(iterative3(10000000))
print(time.time() - x) # 5.61063551902771
seems like your is the fastest(but less readable IMO)
Upvotes: 4