Calculate n + nn + nnn + ? + n(m times) in Python

There are a variety of mathematical series which Python can handle gracefully. One such series involves repeated digits where we take a digit n and create a sequence: n + nn + nnn + ... up to m terms. For example, with n=2 and m=4, we get: 2 + 22 + 222 + 2222 = 2468.

Approach

We convert the digit to a string and concatenate it repeatedly to form numbers with multiple occurrences of the same digit. Then we sum all these generated numbers ?

Example

def sum_of_series(n, m):
    # Convert the digit to string
    str_n = str(n)
    total_sum = 0
    current_number = ""
    
    for i in range(m):
        # Build number with repeated digits
        current_number = current_number + str_n
        total_sum = total_sum + int(current_number)
    
    return total_sum

# Take inputs
n = 2
m = 4
result = sum_of_series(n, m)
print(f"For n={n} and m={m} terms:")
print(f"Series: {n} + {n}{n} + {n}{n}{n} + {n}{n}{n}{n}")
print(f"Sum: {result}")

Output

Running the above code gives us the following result ?

For n=2 and m=4 terms:
Series: 2 + 22 + 222 + 2222
Sum: 2468

Alternative Approach Using Mathematical Formula

We can also calculate this series using a mathematical formula without string concatenation ?

def sum_of_series_formula(n, m):
    total_sum = 0
    
    for i in range(1, m + 1):
        # Calculate n * (10^i - 1) / 9
        term = n * (10**i - 1) // 9
        total_sum += term
        
    return total_sum

# Test with same values
n = 2
m = 4
result = sum_of_series_formula(n, m)
print(f"Using formula approach: {result}")

# Show individual terms
print("Individual terms:")
for i in range(1, m + 1):
    term = n * (10**i - 1) // 9
    print(f"Term {i}: {term}")

Output

Using formula approach: 2468
Individual terms:
Term 1: 2
Term 2: 22
Term 3: 222
Term 4: 2222

Comparison

Method Approach Best For
String Concatenation Build numbers as strings Easy to understand
Mathematical Formula Use formula (10^i - 1) / 9 More efficient for large numbers

Conclusion

Both methods effectively calculate the series n + nn + nnn + ... The string concatenation approach is more intuitive, while the mathematical formula is more efficient for larger values. Choose based on your specific requirements and performance needs.

Updated on: 2026-03-15T17:05:27+05:30

565 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements