-
백준 1789(JAVA) - 수들의 합Algorithm 2022. 11. 10. 09:49728x90
오랜만에 중간고사 시험을 종료하고 다시 코테의 세계로 돌아왔다. 오늘 풀어본 문제는 백준 1789번 수들의 합 문제이다.
이 문제는 문제 길이 만큼이나 생각을 쉽게 하면 매우 간단하게 풀린다.
서로 다른 N개의 자연수의 합이 S라고 한다. S를 알 때, 자연수 N의 최댓값은 얼마일까? 이게 문제인데
예를 들어, S=200이라고 해 보자. S가 200이 되기 위해서는 1+2+3+ ... +19가 되어야 한다. 이 때 출력값 N=19가 되는 것이다.
알고리즘
1. long형으로 S를 입력받는다.
2. 합을 보여주기 위한 sum 변수와 1부터 싹 더해 줄 count 변수를 선언한다.
3. 무한 반복문으로 sum 변수에 count를 계속 더해준다.
4. 만약 1부터 계속 더해준 sum 변수가 입력값 S보다 더 커지는 순간 break를 해준다.
5. count는 계속 ++ 시켜준다.
6. 반복문을 빠져나오는 시점이 sum > S의 상황이므로 이 때의 count 값은 빼주어야한다.
7. count - 1 한 값을 출력시키면 끝
이 알고리즘을 따라 문제를 풀어보았다. 6번이 핵심이다. 반복문을 언제 빠져 나오는지를 명확히 파악해야 쉽게 해결할 수 있는 문제였다. 6번이 이해가 안될 수 있는데 200을 예로 들어보면 1+2+3+...19+20 이 시점에서 sum > S가 되므로 반복문을 빠져나오게 된다. 이때 count를 제외해 주어야 하므로 count - 1 해주어야 하는 것이다.
이렇게 손 쉽게 해결 완료!!!
728x90'Algorithm' 카테고리의 다른 글
백준 10814(JAVA) - 나이순 정렬 (0) 2022.11.14 백준 4673(JAVA) - 셀프 넘버 (0) 2022.11.14 백준 14659 - 한조서열정리하고옴ㅋㅋ(JAVA) (0) 2022.10.05 백준 2163 - 초콜릿 자르기(JAVA) (1) 2022.10.05 백준 9506 - 약수들의 합(JAVA) (1) 2022.10.03