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
Selected Reading
Python Program to calculate n+nm+nmm.......+n(m times).
Here we need to calculate a series where each term is formed by repeating digit n multiple times: n + nn + nnn + ... up to m terms. For example, if n=3 and m=4, the series would be 3 + 33 + 333 + 3333.
Algorithm
Step 1: Input n and m values Step 2: Convert n to string for concatenation Step 3: Initialize sum with first term (n) Step 4: Build each term by concatenating n repeatedly Step 5: Convert string back to integer and add to sum Step 6: Return final sum
Example
Let's implement the solution to calculate the series sum ?
def sum_of_series(n, m):
str_n = str(n)
total_sum = n
current_term = str_n
for i in range(1, m):
current_term = current_term + str_n
total_sum = total_sum + int(current_term)
return total_sum
# Example usage
n = 3
m = 5
result = sum_of_series(n, m)
print(f"For n={n} and m={m}")
print(f"Series: 3 + 33 + 333 + 3333 + 33333")
print(f"Sum of series: {result}")
For n=3 and m=5 Series: 3 + 33 + 333 + 3333 + 33333 Sum of series: 37035
Step-by-Step Breakdown
Let's trace through the example with n=3 and m=5 ?
def sum_of_series_detailed(n, m):
str_n = str(n)
total_sum = n
current_term = str_n
print(f"Term 1: {n}")
for i in range(1, m):
current_term = current_term + str_n
term_value = int(current_term)
total_sum = total_sum + term_value
print(f"Term {i+1}: {term_value}")
return total_sum
n = 3
m = 5
result = sum_of_series_detailed(n, m)
print(f"\nTotal sum: {result}")
Term 1: 3 Term 2: 33 Term 3: 333 Term 4: 3333 Term 5: 33333 Total sum: 37035
Alternative Mathematical Approach
We can also solve this using a mathematical formula without string concatenation ?
def sum_of_series_math(n, m):
total_sum = 0
for i in range(1, m + 1):
# Calculate n repeated i times: n * (10^i - 1) / 9
term = n * (10**i - 1) // 9
total_sum += term
return total_sum
# Test with same values
n = 3
m = 5
result = sum_of_series_math(n, m)
print(f"Using mathematical approach: {result}")
Using mathematical approach: 37035
Comparison
| Method | Approach | Time Complexity | Best For |
|---|---|---|---|
| String Concatenation | Build terms as strings | O(m²) | Easy to understand |
| Mathematical Formula | Direct calculation | O(m) | Better performance |
Conclusion
The string concatenation method is intuitive and easy to understand, while the mathematical approach using the formula n×(10^i?1)/9 is more efficient. Both methods correctly calculate the series n + nn + nnn + ... for m terms.
Advertisements
