在 Python 程式中計算 n + nn + nnn + u + n(m 次)
在本文件中,我們將編寫程式碼計算序列n + nn + nnn + ... + n (m 次) 的總和。我們可以非常輕鬆地在 Python 中實現這一點。我們來看一些示例。
Input: n = 1 m = 5 Series: 1 + 11 + 111 + 1111 + 11111 Output: 12345
演算法
按照以下步驟解決該問題。
1. Initialise the n and m. 2. Initialise total to 0. 3. Make the copy of n to generate next number in the series. 4. Iterate the loop m times. 4.1. Add n to the total. 4.2. Update the n with n * 10 + copy_n. 5. Print the total.
示例
參見以下程式碼。
# initializing n and m n = 1 m = 5 # initializing total to 0 total = 0 # making the copy of n to get next number in the series copy_n = n # iterating through the loop for i in range(m): # adding n to total total += n # updating n to get next number in the serias n = n * 10 + copy_n # printing the total print(total)
輸出
如果執行以上程式碼,你將得到以下結果。
12345
結語
如果你對本文件有任何疑問,請在評論區提及。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP