π Day 29/150 – Sum of First N Natural Numbers in Python
Finding the sum of first N natural numbers is a classic beginner problem that helps you understand loops, formulas, and basic arithmetic in Python.
π Natural numbers start from 1
Examples: 1, 2, 3, 4, 5...
If N = 5
Sum = 1 + 2 + 3 + 4 + 5 = 15
Let’s explore different methods π
πΉ Method 1 – Using for Loop
The most common approach.
n = 5 total = 0 for i in range(1, n + 1): total += i print("Sum:", total)
✅ Explanation:
- Start total = 0
- Add each number from 1 to N
- Print final sum
πΉ Method 2 – Using Formula
Fastest mathematical solution.
n = 5 total = n * (n + 1) // 2 print("Sum:", total)
✅ Explanation:
Formula:
- Very efficient
- No loop required
πΉ Method 3 – Taking User Input
Interactive version.
n = int(input("Enter a number: ")) total = n * (n + 1) // 2 print("Sum:", total)πΉ Method 4 – Using while Loop
Condition-based approach.
n = 5 i = 1 total = 0 while i <= n: total += i i += 1 print("Sum:", total)π― Final Thoughts
- Use formula for best performance ⚡
- Use loop methods for learning logic π§
.png)

0 Comments:
Post a Comment