0
0
PythonProgramBeginner · 2 min read

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 user
2
Initialize a variable to store the sum as 0
3
For each number from 1 to n, square the number and add it to the sum
4
After the loop ends, return or print the sum
💻

Code

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'

ii^2Running Sum
111
245
3914
💡

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.

ApproachTimeSpaceBest For
Generator expressionO(n)O(1)Clean and readable code
For loopO(n)O(1)Beginners learning loops
Mathematical formulaO(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).