1789번: 수들의 합

Joo·2022년 11월 18일

백준

목록 보기
68/113

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

문제

서로 다른 N개의 자연수의 합S라고 한다. S를 알 때, 자연수 N의 최댓값은 얼마일까?

입력

첫째 줄자연수 S(1 ≤ S ≤ 4,294,967,295)가 주어진다.

출력

첫째 줄에 자연수 N의 최댓값을 출력한다.

예제 입력 1

200

예제 출력 1

19

풀이

  • 입력을 long으로 받는 부분 주의

package binary_search;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main_1789 {

    private static long targetNumber;
    private static long result;

    public static void main(String[] args) throws IOException {
        input();
        process();
        output();
    }

    private static void input() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        targetNumber = Long.parseLong(br.readLine());
    }

    private static void process() {
        binarySearch(1L, targetNumber);
    }

    private static void binarySearch(long minCount, long maxCount) {
        long currentCount = (minCount + maxCount) / 2;

        if (minCount > maxCount) {
            return;
        }

        if (isPossible(currentCount)) {
            result = currentCount;
            minCount = currentCount + 1;
        } else {
            maxCount = currentCount - 1;
        }

        binarySearch(minCount, maxCount);
    }

    private static boolean isPossible(long currentCount) {
        long sum = 0;

        for (long i = 1; i <= currentCount; i++) {
            sum += i;
        }

        if (targetNumber >= sum) {
            return true;
        }

        return false;
    }

    private static void output() {
        System.out.println(result);
    }

}

0개의 댓글