In this tutorial, we’ll learn how to write a program to find the sum of the first N natural numbers. The series looks like this: 1 + 2 + 3 + … + N. We’ll go through the logic step-by-step and write a function in Python to solve the problem efficiently.

Problem Explanation

Given a positive integer N, we need to find the sum of the first N natural numbers. The sum can be calculated using a simple mathematical formula, which we’ll explain below.

Examples

  1. Input: N = 1
    • Output: 1
    • Explanation: The series is just 1, so the sum is 1.
  2. Input: N = 5
    • Output: 15
    • Explanation: The series is 1 + 2 + 3 + 4 + 5, and the sum is 15.

Formula for the Sum of the First N Natural Numbers

The sum of the first N natural numbers can be found using the formula: Sum=N×(N+1)/2

This formula is derived from the arithmetic series sum and allows us to calculate the sum in constant time O(1).

Steps to Write the Program

  1. Input: The function will take a single integer N as input.
  2. Calculate the Sum: Use the formula mentioned above to calculate the sum.
  3. Return the Result: The function will return the calculated sum.

Function Signature

python code
def seriesSum(N: int) -> int:
    pass

Python Code Implementation

Here’s the complete function to solve the problem:

pythoncode
def seriesSum(N: int) -> int:
    # Calculate the sum using the formula
    sum_of_series = N * (N + 1) // 2
    return sum_of_series

Explanation

  1. Input: The function takes an integer N as an input parameter.
  2. Calculation: The formula N * (N + 1) // 2 is used to calculate the sum of the first N natural numbers. We use integer division // to ensure the result is an integer.
  3. Return: The function returns the calculated sum.

Example Walkthrough

Let’s walk through the second example:

Input: N = 5

  • Calculate the sum: Sum=5×(5+1)/2=5×6/2=15
  • The function will return 15.

Time and Space Complexity

  • Time Complexity: O(1) because the calculation is done in constant time.
  • Space Complexity: O(1) because no extra space is used except for a few variables.

Conclusion

By using the arithmetic series sum formula, we can efficiently find the sum of the first N natural numbers. This method is both simple and optimal, ensuring that our program runs in constant time regardless of the size of N.

Try implementing this function yourself and test it with different values of N to see how it works!

Leave a Reply

Your email address will not be published. Required fields are marked *