Python Program for Sum of Squares of First N Natural Numbers

1. Introduction

The sum of squares of the first n natural numbers is a common problem that helps in understanding mathematical sequences and series. It involves adding up the squares of all numbers from 1 to n. This sum has a direct formula, but it can also be calculated using a loop, which is more illustrative for beginners in programming. This blog post will demonstrate how to calculate this sum in Python, both by using the direct formula and by iterating through the numbers.

2. Program Steps

1. Prompt the user to enter the value of n.

2. Calculate the sum of squares using the direct formula: n(n + 1)(2n + 1) / 6.

3. Alternatively, calculate the sum of squares by iterating from 1 to n and summing the squares of these numbers.

4. Display the result to the user.

3. Code Program

# Step 1: Get the value of n from the user
n = int(input("Enter the value of n: "))

# Function to calculate the sum of squares using the direct formula
def sum_of_squares_formula(n):
    return n * (n + 1) * (2 * n + 1) // 6

# Function to calculate the sum of squares by iteration
def sum_of_squares_iterative(n):
    sum_squares = 0
    for i in range(1, n + 1):
        sum_squares += i * i
    return sum_squares

# Calculate the sum of squares using both methods
sum_squares_formula = sum_of_squares_formula(n)
sum_squares_iterative = sum_of_squares_iterative(n)

# Display the results
print(f"Sum of squares of first {n} natural numbers (formula): {sum_squares_formula}")
print(f"Sum of squares of first {n} natural numbers (iterative): {sum_squares_iterative}")

Output:

Enter the value of n: 5
Sum of squares of first 5 natural numbers (formula): 55
Sum of squares of first 5 natural numbers (iterative): 55

Explanation:

1. The user inputs the number n, which denotes the range of natural numbers for which the sum of squares is to be calculated.

2. The program defines two functions to calculate this sum: sum_of_squares_formula uses the direct mathematical formula n(n + 1)(2n + 1) / 6 to find the sum efficiently. This method leverages the algebraic solution to the problem, providing the result in constant time.

3. The sum_of_squares_iterative function calculates the sum by iterating from 1 to n, squaring each number, and accumulating the total sum. This method is more illustrative and shows the process of summing the squares one by one.

4. Both methods are called with the user-provided value of n, and the results are displayed. The output confirms that both methods yield the same result, demonstrating two different approaches to solving the problem: a direct formula and an iterative sum.


Comments