Post

[백준] 1789번 - 수들의 합 [Java][C++]

[백준] 1789번 - 수들의 합 [Java][C++]

문제 링크


1. 문제 풀이

서로 다른 $N$ 개의 자연수의 합이 $S$ 일 때, $S$ 를 알려주고 $N$ 의 최댓값을 구하는 문제다. $N$ 이 최대한 커지려면 최대한 작은 자연수로 $S$ 의 합을 이루면 되며 이는 $1$ 부터 쭉 더해나가면 된다. $1$ 부터 연속한 자연수의 합인 $\dfrac{n \times (n+1)}{2}$ 를 활용하여 $S$ 보다 작거나 같은 동안 $n$ 을 늘리며 비교한 후 $n - 1$ 을 반환하면 된다.


2. 코드

1. 수학 [Java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        long S = Long.parseLong(br.readLine());

        long n = 1;
        while (n * (n + 1) / 2 <= S) {
            n++;
        }

        System.out.println(n - 1);
    }
}

2. 수학 [C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    long long s;
    cin >> s;

    long long n = 1;
    while (n * (n + 1) / 2 <= s) {
        n++;
    }

    cout << n - 1;
}

3. 풀이 정보

1. 수학 [Java]

언어시간메모리코드 길이
Java 11104 ms14244 KB365 B

2. 수학 [C++]

언어시간메모리코드 길이
C++ 170 ms2020 KB245 B

This post is licensed under CC BY 4.0 by the author.