在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

结论