Multiple ways to Find Sum of Natural Number in Python

In this Python example, we will cover the program to calculate the sum of the n natural numbers.

1. What is a Natural Number?

In mathematics, the natural numbers are those numbers used for counting and ordering.

– Wikipedia

Natural numbers can be considered as the subset of the Real number that includes only the positive integers i.e. 1, 2, 3, 4… up to infinity, and does not include zero, decimal values, fractions, and negative numbers.

The sum of the natural numbers depends on the number of terms we want to add.

Example:
Input : 5  #Sum of first 5 terms
Output : 15

Input : 9  #Sum of first 10 terms
Output : 45

Some of the topics which will be helpful for understanding the program implementation better are:

Let’s go through each of the implementation methods one by one.


2. Python Program to find Sum of N Natural Numbers

2.1. Using The For Loop – Iteration Method

The input from the user has been taken and the for loop has been used along with simple if-else condition to perform the operation.

# Python Program for Sum of n Natural Numbers
val = int(input("Enter the nth-term to find sum : "))

if val < 0:
  print("Wrong Input")
else:
  sumvalue = 0
  for i in range(1,val+1):
    sumvalue += i
    
print("The sum is:", sumvalue)
Output
Enter the nth-term to find sum : 21
The sum is: 231

2.2. Using N-Term Sum Formula

To find the sum of n natural numbers, we can directly apply the formula.

sum = n*(n+1)/2

# Python program to find sum of natural number using formula
n = int(input("Enter the value of n to find sum : "))
sum = n * (n+1)//2
print("The sum of provided n terms is:", sum)
Output
Enter the value of n to find sum : 45
The sum of provided n terms is 1035

We should prefer to use the formula for calculating the sum as it is fas, consumes less memory and complexity is of order O(1)


3. Conclusion

In this Python example, we discussed how to find the add n natural number using loop and using the formula approaches.


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! 😊

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x