- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculate n + nn + nnn + … + n(m times) in Python program
We are going to write a program that calculates the following series in Python. Examine the example inputs and outputs for the program that we are going to write.
Input: 34 3 + 33 + 333 + 3333 Output: 3702
Input: 5 5 5 + 55 + 555 + 5555 + 55555 Output: 61725
So, we will have two numbers, and we have to calculate the sum of the series generated as above. Follow the below steps to achieve the output.
Algorithm
1. Initialize the number let's say n and m. 2. Initialize a variable with the value n let's say change. 3. Intialize a variable s to zero. 4. Write a loop which iterates m times. 4.1. Add change to the s. 4.2. Update the value of change to get next number in the series. 5. Print the sum at the end of the program.
You have to create a general formula to generate numbers in the series. Try to get it as your own. If you stuck at the logic, see the code below.
Example
## intializing n and m n, m = 3, 4 ## initializing change variable to n change = n ## initializing sum to 0 s = 0 ## loop for i in range(m): ## adding change to s s += change ## updating the value of change change = change * 10 + n ## printing the s print(s)
Output
If you run the above program, you will get the following output.
3702
Let's see another example with different values as we discussed in the examples.
Example
## intializing n and m n, m = 5, 5 ## initializing change variable to n change = n ## initializing sum to 0 s = 0 ## loop for i in range(m): ## adding change to s s += change ## updating the value of change change = change * 10 + n ## printing the s print(s)
Output
If you run the above program, you will get the following output.
61725
Conclusion
If you have any doubts regarding the tutorial, mention them in the comment section.
Advertisements