Sum of First N Natural Numbers in Python
Replace a long addition with N(N+1)/2 in Python. A first-year exercise explains the pairing idea, exact integer division, and the positive-input requirement.
1# Program to find the sum of first N natural numbers23n = int(input("Enter a positive integer N: "))45if n <= 0:6 print("Please enter a positive integer.")7else:8 total = n * (n + 1) // 29 print("Sum of first", n, "natural numbers is:", total)
Sample Output
Sum of first 10 natural numbers is: 55
10 × 11 divided by 2 gives the exact integer 55.
In this one
- Explain the consecutive-integer sum formula
- Keep an exact integer result
- Compare a formula with repeated addition
How it works
- 1
Read a positive integer n.
- 2
Reject zero or a negative input before computing.
- 3
Evaluate n * (n + 1) // 2 and print total.
Edge cases
One term
Enter 1.
The formula gives 1 * 2 // 2, so the sum is 1.
Zero terms
Enter 0.
This implementation prints its positive-integer message rather than the empty sum 0.
What's going on
1 + 2 + ... + N equals N(N+1)/2. Pair the first and last terms: each pair has the same total, N+1. That is why a whole sum can become one expression.
The code rejects n <= 0 because the prompt asks for a positive count. For n = 10 it computes 10 * 11 // 2, which is 55. The product of consecutive integers is always even, so this particular // division loses no remainder.
Regular / would return 55.0, a float. // keeps the calculation in integers. A loop adding each term is also correct, but does work once per term. The formula uses a fixed number of arithmetic operations; very large Python integers still take more work as their digit count grows. Neither version needs floating-point arithmetic for this problem.
After this program
If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why is // exact in this formula?
Pick an answer to check it.
Question 2
What changes if / replaces //?
Pick an answer to check it.
Questions people ask
Why is // exact in this formula?
One of n and n + 1 is even, so their product is divisible by 2.
What changes if / replaces //?
/ returns a float, while // keeps the exact integer calculation here.
Is a loop wrong for this sum?
No. A loop is a useful way to learn accumulation, but it visits every term.