Question:
php homework question, calculate sum of squares?
Lulu
2011-03-01 15:58:10 UTC
I don't need help with the code, but with the logic behind it. This is the question:
Write a program that accepts an integer larger than 1 and calculates the sum of the squares from 1 to that integer. For example, if the integer equals 4, the sum of the squares is 30 (1 + 4 + 9 + 16, notice 4 numbers)

Things to keep in mind..

I'm not getting user input, I'll just create a variable and manually assign the value of the integer.
I think the best way is a while loop, defining a variable for the integer, one for the square operation and incrementing the integer (or decrementing?) to get to all the numbers' squares before that integer, and a sum variable that I will echo out including a (constant for 1?) + squares of numbers in between + the actual integer's square

Any thoughts?

I'm new at this and I have no idea about libraries yet. It's plain math that I can't figure out.

Like I said, I'm not looking for code but just the logic :)

Thanks!
Three answers:
?
2011-03-01 16:01:17 UTC
Luckily there is a very quick formula you can use!



I won't prove it, but the sum of the square numbers from 1 to n² (i.e, 1+4+9+16+....+n²) is:



S = n(n+1)(2n+1)/6



(Checking it works with n=4 gives 4(4+1)(8+1)/6 = 4(5)(9)/6 = 180/6 = 30 as required!)
anonymous
2011-03-01 16:11:33 UTC
best way would be a for loop b/c you know you need to go from 1 to n and add 1 each time

in the loop you simply square the current value of the loop counter and add to the sum variable

(constant for 1?) ... i dont know

squares of numbers in between ... you mean print out "(1+4+9+16+...)" or add those numbers except the nth one?

actual integer's square ... is this n² or the value you determine in the loop?
carrabotta
2016-12-13 01:15:22 UTC
The area that has been cut back off is likewise a sq.-based pyramid. think of the full pyramid. Subtract the quantity of the sliced off area from the quantity of the full pyramid. i might ought to take a minute to absolutely convince myself of this, yet i'm quite specific that the area length of a slice like that is going to be proportional to distance from the precise of the pyramid. this is, the certainty that the area length is two the place the slice happens, and the area length is 4 on the backside, potential that the slice is a million/2 of how from the precise to the backside. So the full pyramid is 12 contraptions extreme, and the little pyramid that has been sliced off is 6 contraptions extreme.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...