使用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)
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
如果您运行上面的程序,您将得到以下输出。
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
结论
如果您对本教程有任何疑问,请在评论部分提出。
广告