Reputation: 3
I have a math question.
Having a sum of number from 1 to n. For example it may be:
sum([i for i in range(46)])
So the sum of it equals 1035.
Now my question is, knowing just sum - 1035 and that we start from 1. I want to calculate n.
How can I do that
Upvotes: 0
Views: 126
Reputation: 3197
The summation will actually start from 0 and it will go to 45. You can test this by printing out the values:
for i in range(46):
print(i)
To reverse the summation you will want to use the formula for sum of first n numbers, n*(n+1)/2 and equate this to the sum, 1035.
solving the equation you will get the quadratic n^2 + n - 2070 = 0
now you will need to get the roots. Only the positive root will matter in this case, we will use the quadratic formula to get the roots:
D = 1^2 - 41(-2070);
x = (-1 + sqrt(D) / 2)
(math.sqrt(sum(i for i in range(46))*8 + 1) - 1) / 2
this will give you the last value that was added, 45. Now you can just add 1 to this to get 46.
Upvotes: 0
Reputation: 73
You could try something like :
import math
def find_n_sum(s):
d=1+8*s
if (-1+math.sqrt(d))%2 == 0:
return (-1+math.sqrt(d))/2
else:
return "Text to return if it doesn't exist"
Upvotes: 0
Reputation:
The sum of the first n integers is n*(n+1)/2
So using the quadratic formula (and skipping the possibility of no real roots)
import math
s = 1035
n = (-1 + math.sqrt(1 + 8*s))/2 # the other root is negative
print(n)
45.0
which in python3 division is a float.
Note too -- although you probably knew this -- that range(46)
sums 1 + 2 + .... + 45. The upper end of range
is excluded.
Upvotes: 1
Reputation: 328
The formula to calculate sum of upto n
numbers is n*(n+1)/2
.
checkout https://brilliant.org/wiki/sum-of-n-n2-or-n3/
Upvotes: 0