使用Python程式計算 n + nn + nnn + … + n(m次)
我們將編寫一個Python程式來計算以下級數。檢視我們將要編寫的程式的示例輸入和輸出。
Input: 34 3 + 33 + 333 + 3333 Output: 3702
Input: 5 5 5 + 55 + 555 + 5555 + 55555 Output: 61725
因此,我們將有兩個數字,我們必須計算如上生成的級數的和。請按照以下步驟實現輸出。
演算法
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.
您必須建立一個通用的公式來生成級數中的數字。嘗試自己獲得它。如果您卡在邏輯上,請參見下面的程式碼。
示例
## 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)
輸出
如果您執行上面的程式,您將得到以下輸出。
3702
讓我們看看另一個使用不同值的示例,正如我們在示例中討論的那樣。
示例
## 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)
輸出
如果您執行上面的程式,您將得到以下輸出。
61725
結論
如果您對本教程有任何疑問,請在評論部分提出。
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP