coding in python that it sums a number that the user will give

64 Views Asked by At

i want to make a python program that ask from the user a number and the program should sums up the first n squares as long as the sum is smaller (not smaller than or equal to) than the numb er that the user has choose before Like this line

1+2**2 +3**2+4**2 +....+n2 < the number that the user choose

For example if the the number 20, n is 3 the result will be 1 + 4 + 9 < 20

4

There are 4 best solutions below

0
On

The easiest way is to sum up the squares until the sum is greater than or equal to the chosen number and then remove the last square. (That is, subtract $1$ at the end).

0
On

To make it more about maths: $$\sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6}$$

which allows us to make an estimate for $n$ given the entered number $m$: $n$ is about $\sqrt[3]{3m}$, so start there and go up a few to see when you cross $m$.

0
On

Approach 1: Direct approach

n=int(input(" Enter a number"))

sum=0

sumlist=[]

i=1

while $sum<n$:

sum=sum+i**2

sumlist.append(sum)

i=i+1

print(sumlist[-2])

Approach2: Mathematical approach

Alternatively using the formula $\sum_{i=1}^k i^2 = \frac{k(k+1)(2k+1)}{6}$:

n=int(input(" Enter a number"))

i=1

while (i*(i+1)*(2*i+1)/6) $<n:$

i=i+1

print(int((i-1)(i)(2*i-1)/6))

Note: Grey text should be indented

0
On

Using the same idea as Henno Brandsma, consider that you look for the zero of function $$f(n)=\frac{n(n+1)(2n+1)}{6}-m$$ and use Newton method with $n_0=\sqrt[3]{3m}$. Since $$f(n_0)>0\qquad \text{and} \qquad f''(n_0)>0$$ by Darboux theorem, you will never have an overshoot of the solution. Stop iterating when $n_{k+1}-n_k <1$. This would be very fast.

Now, if you want to consider very large values of $m$, let me know since we can find very good approximation of the solution.

Edit

There is an exact solution to the problem. Solving the cubic equation lead to $$n=\left\lfloor \frac{\cosh \left(\frac{1}{3} \cosh ^{-1}\left(36 \sqrt{3} m\right)\right)}{\sqrt{3}}-\frac{1}{2}\right\rfloor$$