Sum of n Natural Numbers in Python

Video Tutorial
FREE
Print Sum of Numbers in given Range thumbnail
This video belongs to
Python Course for Beginners With Certification: Mastering the Essentials
16 modules
Certificate
Topics Covered

Overview to Find the Sum of First n Natural Numbers

The natural numbers are the positive numbers, and the least natural number is 1. We can find the sum of n natural numbers using a single transversal loop or a mathematical formula.

Program to Find the Sum of First n Natural Numbers

Suppose you want to find the sum of n natural numbers in python. There are multiple ways to find the sum of first n natural numbers. Let's discuss each method one by one.

Sum of Natural No

Using Recursion

We can use recursion to the sum of n natural numbers in python. Let's understand using an example of how to use recursion to find the sum of n natural numbers.

In the below program, we are calculating the sum of the first n natural number using recursion. The sum() method is recursively called in the decreasing order of natural numbers until the natural number becomes equal to 1.

Output:

The sum of the first 5 natural numbers is 15.

Note:

  • The time complexity of this approach is O(n).
  • The space complexity is O(n) because we use the stack memory to perform the recursive call while calculating the sum of natural numbers.

Using For Loop

Let's understand how to use for loop to find the sum of n natural numbers in python

In the below program, we are using a for loop that is iterating on the range of [1-n] and storing the sum in a variable, let's say sum in this case.

Output:

Note:

  • The time complexity of this approach is O(n).
  • The space complexity of this approach is O(1).

Using Formula

We can find the sum of n natural numbers in python in the time complexity O(1) and the space complexity of O(1). Let's first understand the formula behind this.

The formula is (n*(n+1))/2, where n represents the first n natural numbers.

Let's understand this formula.

Sum of first n natural numbers=(n*(n+1)/2)

Examples:

n=5
Sum=(5*(5+1))/2=(5*6)/2=30/2=15
The sum of the first 5 natural numbers is 15.

Let's understand how to use the above formula using an example.

Output:

The sum of natural numbers up to 5 is 15.

Explore Scaler Topics Python Tutorial and enhance your Python skills with Reading Tracks and Challenges.

Conclusion

  • The least natural number is 1.
  • The formula to find the sum of the first n natural number is n*(n+1)/2.
  • Recursion process requires more space than iteration to find the sum of natural numbers.
  • The Worst space complexity occurs in the recursion method to find the sum of n natural numbers.

See Also: