Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Read a Number n And Print the Series "1+2+.....+n=
When it is required to display the sum of all natural numbers within a given range and show the series format "1+2+...+n=sum", we can create a program that builds the series string and calculates the sum.
Below is a demonstration of the same ?
Method 1: Using Loop to Build Series
Example
def print_series_sum(n):
series = ""
total = 0
for i in range(1, n + 1):
total += i
if i == 1:
series = str(i)
else:
series += "+" + str(i)
return f"{series}={total}"
n = 5
print("The number is:")
print(n)
print("The series is:")
print(print_series_sum(n))
The number is: 5 The series is: 1+2+3+4+5=15
Method 2: Using Formula for Direct Calculation
Example
def print_series_with_formula(n):
# Build series string
series = "+".join(str(i) for i in range(1, n + 1))
# Calculate sum using formula: n*(n+1)/2
total = n * (n + 1) // 2
return f"{series}={total}"
n = 7
print("The number is:")
print(n)
print("The series is:")
print(print_series_with_formula(n))
The number is: 7 The series is: 1+2+3+4+5+6+7=28
Method 3: Interactive Input Version
Example
def display_natural_sum():
n = int(input("Enter a number: "))
# Build and display the series
series_parts = []
total = 0
for i in range(1, n + 1):
series_parts.append(str(i))
total += i
series = "+".join(series_parts)
print(f"{series}={total}")
# Call the function
display_natural_sum()
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| Loop Method | O(n) | Small numbers, learning |
| Formula Method | O(n) for string, O(1) for sum | Efficient calculation |
| Interactive Version | O(n) | User input programs |
How It Works
The program builds a string showing the series "1+2+3+...+n"
It calculates the sum of natural numbers from 1 to n
The formula n*(n+1)/2 provides an efficient way to calculate the sum
String joining methods like
"+".join()create clean series outputThe final result displays both the series and its sum
Conclusion
Use the formula method for efficient calculation of large numbers. The loop method is better for understanding the concept and building the visual series representation.
