Sum of squares of first N natural numbers - Python
Last Updated : 02 May, 2025
The goal here is to calculate the sum of squares of the first n natural numbers. The sum of squares is the result of adding up the squares of each number from 1 to n. For example, if n = 5, the sum of squares would be 12 + 22 + 32+ 42+52=55. Let's explore different methods to compute this sum efficiently.
This method uses mathematical formula to directly compute the sum of squares of the first n natural numbers. It is the most efficient and fastest approach since it avoids any iteration and performs the calculation in constant time.
Mathematical Formula Python n = 5 res = n * (n + 1) * (2 * n + 1) // 6 print(res)
Explanation: For n = 5, the expression becomes 5 * 6 * 11 // 6, which equals 330 // 6, giving the final result 55. The // operator performs integer division, ensuring the result is returned as a whole number without any decimal part.
Using generator expression
Generator expression inside the built-in sum() function to calculate the square of each number and sum them. It’s simple and memory-efficient because it doesn't store all the values in memory (unlike a list comprehension).
Python n = 5 res = sum(x * x for x in range(1, n + 1)) print(res)
Explanation: Generator function generates the square of each number x in the range from 1 to n. For n = 5, it calculates 1² + 2² + 3² + 4² + 5², resulting in 55.
Using reduce
reduce() function from Python’s functools module applies a lambda function cumulatively to the items of the sequence, reducing them to a single value here, summing up the squares of numbers.
Python from functools import reduce n = 5 res = reduce(lambda x, y: x + y * y, range(1, n + 1), 0) print(res)
Explanation: reduce() applies the lambda x + y * y to the numbers from 1 to n, starting with 0. For n = 5, it calculates 0 + 1² + 2² + 3² + 4² + 5², resulting in 55. In each step, y is squared and added to the accumulated total x, effectively summing the squares.
Using for loop
This is the most traditional and beginner-friendly method. It uses a simple for loop to iterate from 1 to n, calculating the square of each number and adding it to the total.
Python n = 5 total = 0 for i in range(1, n + 1): total += i * i print(total)
Explanation: For loop iterates over each number from 1 to n and for each number i, it calculates i * i and adds it to the running total. For n = 5, the loop calculates 1² + 2² + 3² + 4² + 5², resulting in 55.
Related Articles