Python Program to Find Sum of n Natural Numbers
You can find the sum of n natural numbers in Python using the formula
sum = n * (n + 1) // 2 or by looping from 1 to n and adding each number.Examples
Input5
Output15
Input10
Output55
Input1
Output1
How to Think About It
To find the sum of the first n natural numbers, think of adding all numbers from 1 up to n. You can do this by adding each number one by one or use a simple math formula that calculates the total quickly without adding each number.
Algorithm
1
Get the input number n from the user.2
Use the formula sum = n * (n + 1) // 2 to calculate the sum.3
Print the result.Code
python
n = int(input("Enter a positive integer: ")) sum_natural = n * (n + 1) // 2 print("Sum of", n, "natural numbers is:", sum_natural)
Output
Enter a positive integer: 5
Sum of 5 natural numbers is: 15
Dry Run
Let's trace the example where n = 5 through the code
1
Input
User enters n = 5
2
Calculate sum
sum_natural = 5 * (5 + 1) // 2 = 5 * 6 // 2 = 30 // 2 = 15
3
Output
Print 'Sum of 5 natural numbers is: 15'
| n | Calculation | sum_natural |
|---|---|---|
| 5 | 5 * (5 + 1) // 2 | 15 |
Why This Works
Step 1: Input number
We get the number n from the user to know how many natural numbers to add.
Step 2: Use formula
The formula n * (n + 1) // 2 quickly calculates the sum without looping.
Step 3: Print result
We show the sum to the user with a clear message.
Alternative Approaches
Using a loop
python
n = int(input("Enter a positive integer: ")) sum_natural = 0 for i in range(1, n + 1): sum_natural += i print("Sum of", n, "natural numbers is:", sum_natural)
This method is easy to understand but slower for very large n compared to the formula.
Using recursion
python
def sum_natural(n): if n == 1: return 1 else: return n + sum_natural(n - 1) n = int(input("Enter a positive integer: ")) print("Sum of", n, "natural numbers is:", sum_natural(n))
Recursion is elegant but can cause stack overflow for very large n.
Complexity: O(1) time, O(1) space
Time Complexity
Using the formula takes constant time because it does a fixed number of operations regardless of n.
Space Complexity
The formula uses only a few variables, so space is constant.
Which Approach is Fastest?
The formula method is fastest and most efficient compared to looping or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Formula | O(1) | O(1) | Fastest for any n |
| Loop | O(n) | O(1) | Easy to understand, small n |
| Recursion | O(n) | O(n) | Learning recursion, small n |
Use the formula
n * (n + 1) // 2 for the fastest and simplest solution.Forgetting to convert input to integer or using float division instead of integer division.