[Baekjoon Online Judge] 풀이

[Baekjoon Online Judge] 백준 5341번: Pyramids 파이썬 풀이 - 알고리즘 코딩 문제 해설 python

codeomni 2023. 3. 1. 20:49
반응형

 

안녕하세요.

이번 포스팅은 백준 온라인 저지의 5341 문제 풀이입니다.

문제 이름은 "Pyramids" 입니다.

 

 

문제


문제 링크는 바로 밑의 링크를 확인해주세요.

https://www.acmicpc.net/problem/5341

 

5341번: Pyramids

The input will be a sequence of integers, one per line. The end of input will be signaled by the integer 0, and does not represent the base of a pyramid. All integers, other than the last (zero), are positive.

www.acmicpc.net

 

 

풀이


1
2
3
4
5
6
7
8
while 1:
    n = int(input())
    if n == 0:
        break
    sum = 0
    for i in range(1, n+1):
        sum = sum + i
    print(sum)
cs

 

 

핵심: 입력한 수 만큼 1부터 순차적으로 더합니다.

ex) 4층일 경우:  1 + 2 + 3 + 4

 

1. 0을 입력할 때 까지 반복하므로 while 1을 통해서 무한 반복문을 생성합니다.

 

2. 피라미드의 층 수인 n을 입력받습니다.

 

3~4. 입력한 수가 0일 경우 출력하지 않고 탈출합니다.

 

5~7. for 문을 사용하여 입력한 수까지 합계를 수합니다.

단, 피라미드의 맨 위의 블록은 1개이므로 1부터 시작하고

마지막 n층까지 구해야 하므로 for문의 범위는 (1, n+1)이 됩니다.

 

8. 합계를 출력합니다.