Natural numbers are positive integers starting from 1, 2, 3, 4, 5, ā¦ and so on. The sum of the first N natural numbers is calculated using the formula:
\[S_N = \sum_{i=1}^{N} i = \frac{N (N + 1)}{2}\]For example, the sum of the first 5 natural numbers is:
1+2+3+4+5=15
In this tutorial, we will write a Python program to find the sum of natural numbers using loops, recursion, and a mathematical formula.
Method 1: Using a Loop (Iterative Approach)
python
# Taking user input n = int(input("Enter a positive integer: ")) # Initialize sum variable sum_natural = 0 # Using a loop to calculate sum for i in range(1, n + 1): sum_natural += i # Printing the result print("Sum of first", n, "natural numbers is:", sum_natural)
Output
Enter a positive integer: 8 Sum of first 8 natural numbers is: 36
Method 2: Using a Mathematical Formula (Fastest Approach)
# Taking user input n = int(input("Enter a positive integer: ")) # Using the formula S = (n * (n + 1)) // 2 sum_natural = (n * (n + 1)) // 2 # Printing the result print("Sum of first", n, "natural numbers is:", sum_natural)
Output
Enter a positive integer: 10 Sum of first 10 natural numbers is: 55
Method 3: Using Recursion
def sum_natural(n): if n == 1: return 1 else: return n + sum_natural(n - 1) # Taking user input n = int(input("Enter a positive integer: ")) # Printing the result print("Sum of first", n, "natural numbers is:", sum_natural(n))
Output
Enter a positive integer: 4 Sum of first 4 natural numbers is: 10