Python Program to Find Sum of First N Natural Numbers

1. Introduction

Calculating the sum of the first N natural numbers is a common problem that can be solved efficiently with a simple mathematical formula. This problem is a good example to demonstrate the power of algorithmic thinking, optimizing a potentially resource-intensive operation into a single-step calculation.

A natural number is a positive integer starting from 1. The sum of the first N natural numbers can be found by using the formula N*(N+1)/2, which is derived from the arithmetic progression of numbers.

2. Program Steps

1. Define the value of N (the number of terms).

2. Use the formula N*(N+1)/2 to calculate the sum.

3. Print the result.

3. Code Program

# Function to calculate the sum of the first N natural numbers
def sum_of_natural_numbers(n):
    # Use the formula to calculate the sum
    return n * (n + 1) // 2

# Define the number of terms
N = 100
# Calculate the sum
sum_of_numbers = sum_of_natural_numbers(N)
# Print the result
print(f"The sum of the first {N} natural numbers is: {sum_of_numbers}")

Output:

The sum of the first 100 natural numbers is: 5050

Explanation:

1. The function sum_of_natural_numbers takes an integer n, representing the number of terms.

2. It calculates the sum using the arithmetic formula n * (n + 1) // 2, which utilizes integer division for an exact result.

3. N is set to 100, and the function sum_of_natural_numbers is called with N to calculate the sum of the first 100 natural numbers.

4. The result, 5050, is stored in sum_of_numbers.

5. The print function outputs the result, stating "The sum of the first 100 natural numbers is: 5050".

6. This demonstrates an efficient calculation, as opposed to using loops or recursion to sum an arithmetic series.

Comments