정리
백준 1789번: 수들의 합 본문
백준 1789번: 수들의 합
1789번: 수들의 합
서로 다른 N개의 자연수의 합이 S라고 한다. S를 알 때, 자연수 N의 최댓값은 얼마일까?
www.acmicpc.net

- 이분 탐색을 활용하여 풀면 되는 전형적인 문제이다.
- start = 1, end = s(입력받은 수)
- mid = (start + end) // 2
- 만약 (mid * (mid + 1) // 2) 가 s보다 작거나 같으면 answer에 mid를 저장하고 이분탐색을 계속 이어 나간다. 참고로, 여기서 (mid * (mid + 1) // 2) 는 1부터 mid까지의 합이다.
- 만약 (mid * (mid + 1) // 2) 가 s보다 크면 end = mid - 1 로 하여 mid 값을 줄인다.
- start가 end보다 작거나 같을 때까지 while문을 돌려서 answer의 최댓값을 구한다.
아래는 파이썬 코드이다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
s = int(input()) | |
start = 1; | |
end = s | |
while start <= end: | |
mid = (start + end) // 2 | |
if mid * (mid + 1) // 2 <= s: | |
answer = mid | |
start = mid + 1 | |
else: | |
end = mid - 1 | |
print(answer) |
'Programming > 백준 BOJ' 카테고리의 다른 글
백준 1251번: 단어 나누기 (0) | 2021.01.11 |
---|---|
백준 1654번: 랜선 자르기 (0) | 2021.01.05 |
백준 2493번: 탑 (0) | 2020.10.12 |
백준 14488번: 준오는 급식충이야!! (0) | 2020.09.30 |
백준 2109번: 순회강연 (0) | 2020.09.30 |
Comments