在 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

结语

如果你对本文档有任何疑问,请在评论区提及。

更新于:02-Jan-2020

319 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.