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 Input a Number n and Compute n+nn+nnn
In this tutorial, we'll write a Python program to input a number n and compute the sum n + nn + nnn. For example, if n = 4, we calculate 4 + 44 + 444 = 492.
The key approach is to convert the number to a string and concatenate it to create the required patterns.
Example
Here's the complete program ?
n = int(input("Enter a value for n: "))
n_str = str(n)
# Create the patterns: nn and nnn
nn = n_str + n_str
nnn = n_str + n_str + n_str
# Calculate the sum: n + nn + nnn
result = n + int(nn) + int(nnn)
print(f"The computed value is: {result}")
Output
Enter a value for n: 4 The computed value is: 492
How It Works
The program follows these steps ?
Take input from the user and convert it to an integer
Convert the number to a string for easy concatenation
Create
nnby concatenating the string twiceCreate
nnnby concatenating the string three timesConvert the string patterns back to integers and sum them with the original number
Display the final result
Alternative Approach Using Mathematical Formula
We can also solve this mathematically without string operations ?
n = int(input("Enter a value for n: "))
# Count digits in n
digits = len(str(n))
# Calculate nn and nnn mathematically
nn = n * (10**digits) + n
nnn = n * (10**(2*digits)) + n * (10**digits) + n
result = n + nn + nnn
print(f"The computed value is: {result}")
print(f"Breakdown: {n} + {nn} + {nnn} = {result}")
Output
Enter a value for n: 4 The computed value is: 492 Breakdown: 4 + 44 + 444 = 492
Comparison
| Method | Approach | Best For |
|---|---|---|
| String Concatenation | Convert to string, concatenate, convert back | Simple and readable |
| Mathematical Formula | Use powers of 10 to build numbers | Works with multi-digit numbers efficiently |
Conclusion
String concatenation provides a straightforward solution to create the pattern n + nn + nnn. The mathematical approach offers better understanding of the underlying number structure and works efficiently for any digit length.
