Python Program to Find Sum of Squares of n Numbers
You can find the sum of squares of n numbers in Python by using a loop or comprehension like
sum(i**2 for i in range(1, n+1)).Examples
Input3
Output14
Input5
Output55
Input1
Output1
How to Think About It
To find the sum of squares of n numbers, think of each number from 1 to n, square it (multiply it by itself), and then add all those squared values together to get the total sum.
Algorithm
1
Get the input number n from the user2
Initialize a variable to store the sum as 03
For each number from 1 to n, square the number and add it to the sum4
After the loop ends, return or print the sumCode
python
n = int(input("Enter a number: ")) sum_squares = sum(i**2 for i in range(1, n+1)) print("Sum of squares:", sum_squares)
Output
Enter a number: 5
Sum of squares: 55
Dry Run
Let's trace the input 3 through the code
1
Input
n = 3
2
Calculate squares
Squares: 1^2=1, 2^2=4, 3^2=9
3
Sum squares
Sum = 1 + 4 + 9 = 14
4
Output
Print 'Sum of squares: 14'
| i | i^2 | Running Sum |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 4 | 5 |
| 3 | 9 | 14 |
Why This Works
Step 1: Loop through numbers
We use a loop or comprehension to go through each number from 1 to n.
Step 2: Square each number
Each number is squared using i**2, which means multiplying the number by itself.
Step 3: Add squares
All squared numbers are added together using sum() to get the final result.
Alternative Approaches
Using a for loop
python
n = int(input("Enter a number: ")) sum_squares = 0 for i in range(1, n+1): sum_squares += i*i print("Sum of squares:", sum_squares)
This method is easy to understand and good for beginners but slightly longer than comprehension.
Using formula n(n+1)(2n+1)/6
python
n = int(input("Enter a number: ")) sum_squares = n*(n+1)*(2*n+1)//6 print("Sum of squares:", sum_squares)
This uses a math formula for sum of squares and is very fast without loops, but requires knowing the formula.
Complexity: O(n) time, O(1) space
Time Complexity
The program loops through numbers from 1 to n once, so it takes linear time O(n).
Space Complexity
It uses a fixed amount of extra space for the sum variable, so space complexity is O(1).
Which Approach is Fastest?
The formula method is fastest with O(1) time, but the loop and comprehension methods are easier to understand and use.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Generator expression | O(n) | O(1) | Clean and readable code |
| For loop | O(n) | O(1) | Beginners learning loops |
| Mathematical formula | O(1) | O(1) | Fastest for large n, needs formula knowledge |
Use a generator expression with
sum(i**2 for i in range(1, n+1)) for clean and efficient code.Beginners often forget to include the last number n in the range, using
range(1, n) instead of range(1, n+1).