Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python 프로그램에서 n + nn + nnn + … + n(m 번) 계산

<시간/>

파이썬에서 다음 급수를 계산하는 프로그램을 작성할 것입니다. 우리가 작성할 프로그램에 대한 예제 입력 및 출력을 검토하십시오.

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

결론

튜토리얼에 대해 궁금한 점이 있으면 댓글 섹션에 언급하세요.