-1

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

Arthur
  • 199,419
UX373
  • 11
  • 1
    I strongly suspect that this question is off-topic here. Besides, even if it were on-topic, we would very much prefer it if you told us things like what you have tried, and where you are stuck. If you have made a couple of similar, simpler programs already ("Sum all integers up to $n$", for instance), you should at least know where to start. – Arthur Mar 25 '19 at 11:38
  • Hint: How would you calculate the sum of first $n$ squares? I mean $1^2 + 2^2 +3^2 + \ldots + n^2$ ? – Matti P. Mar 25 '19 at 11:40
  • @UX373 , for small numbers I have posted the direct solution. For larger numbers, perhaps consider Newton's method as suggested in the comments below – aman Mar 25 '19 at 12:00

4 Answers4

2

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$$

1

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).

Peter
  • 84,454
1

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$.

Henno Brandsma
  • 242,131
0

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

aman
  • 1,294