반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
05-19 00:03
관리 메뉴

ImJay

[파이썬/Python] 백준 5341번 Pyramids 본문

Solved.ac - Python/Bronze V

[파이썬/Python] 백준 5341번 Pyramids

ImJay 2023. 6. 5. 04:31
반응형

[파이썬/Python] 백준 5341번 Pyramids

 

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


문제

A pyramid of blocks is constructed by first building a base layer of n blocks and then adding n-1 blocks to the next layer. This process is repeated until the top layer only has one block.

 

You must calculate the number of blocks needed to construct a pyramid given the size of the base. For example, a pyramid that has a base of size 4 will need a total of 10 blocks.

 

블록으로 구성된 피라미드를 만들 때, 먼저 n개의 블록으로 기초 층을 구성하고, 그 다음 층에는 n-1개의 블록을 추가합니다. 이 과정을 반복하여 맨 위 층에는 하나의 블록만 남게 됩니다.

 

주어진 기초 층의 크기를 바탕으로 피라미드를 구성하는 데 필요한 블록 수를 계산해야 합니다. 예를 들어, 기초 층이 4개인 피라미드는 총 10개의 블록이 필요합니다.

입력

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.

입력은 정수의 시퀀스로 주어집니다. 입력의 끝은 정수 0으로 신호를 보내며, 이는 피라미드의 기초를 나타내지 않습니다. 마지막(0이 아닌) 정수를 제외한 모든 정수는 양수입니다.

출력

For each positive integer print the total number of blocks needed to build the pyramid with the specified base.

각 양수 정수에 대해 지정된 기초로 피라미드를 구성하는 데 필요한 총 블록 수를 출력합니다.

예제 입력

4
6
0

예제 출력

10
21

풀이

while True:
    # 블록 수의 합을 초기화
    sum = 0
    
    # 기초 층의 크기를 입력
    n = int(input())
    
    # 입력값이 0이면 반복을 종료
    if not n:
        break
    
    # 1부터 n까지 반복하며 블록 수를 합산
    for i in range(1, n+1):
        sum += i
    
    # 피라미드를 구성하는 데 필요한 총 블록 수를 출력
    print(sum)

이 프로그램은 입력값 n에 대해 1부터 n까지 반복하여 합산하는 과정을 수행한다. 따라서 시간 복잡도는 O(n)이다. 입력값 n에 비례하여 반복 횟수와 실행 시간이 증가한다. 블록 수의 합산은 상수 시간에 이루어지므로 반복문이 가장 시간이 많이 소요되는 부분이다. 따라서 입력 크기에 따라 선형적으로 실행 시간이 증가한다.

반응형
Comments