Python Program to Find the Sum of Squares of the First N Numbers
Beginner · Numbers
This program adds up the squares of the first n natural numbers, 1^2 + 2^2 + 3^2 and so on up to n^2. For n = 5 that is 1 + 4 + 9 + 16 + 25 = 55, and the answer is checked with the formula n(n + 1)(2n + 1) / 6.
Program
sum_of_squares.py
n = 5 # or: n = int(input("Enter n: "))
total = 0
terms = []
for i in range(1, n + 1):
total += i * i
terms.append(str(i * i))
print(" + ".join(terms), "=", total)
print(f"Sum of the squares of the first {n} numbers: {total}")
# The formula gives the same answer without a loop
formula = n * (n + 1) * (2 * n + 1) // 6
print("Using the formula:", formula)
Output
1 + 4 + 9 + 16 + 25 = 55 Sum of the squares of the first 5 numbers: 55 Using the formula: 55
How it works
- The loop runs
ifrom 1 tonand addsi * i, the square ofi, tototal. - Each square is also saved as text in
terms, so" + ".join(terms)can print the whole sum. - The formula
n * (n + 1) * (2 * n + 1) // 6gives the same result in one step, however bignis. - The product is always divisible by 6, so
//gives the exact whole number.
Other ways to write it
Using sum() and a generator
Using sum() and a generator
n = 10
total = sum(i ** 2 for i in range(1, n + 1))
print(f"Sum of the squares from 1 to {n}: {total}")
Output
Sum of the squares from 1 to 10: 385
sum() adds up the squares as the generator produces them, without building a list first.
Sum of cubes
Sum of cubes
n = 5
cubes = sum(i ** 3 for i in range(1, n + 1))
square_of_sum = (n * (n + 1) // 2) ** 2
print("Sum of the cubes from 1 to", n, "is", cubes)
print("Square of the sum 1 to", n, "is", square_of_sum)
Output
Sum of the cubes from 1 to 5 is 225 Square of the sum 1 to 5 is 225
The sum of the first n cubes always equals the square of the sum of the first n numbers: here both are 225.
Try it yourself
Find the difference between the square of the sum and the sum of the squares for the first 10 numbers.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises