![]() |
VOOZH | about |
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.
55
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.
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).
55
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.
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.
55
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.
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.
55
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.