Post

[BaekJoon] #8393 - 합 [Java][C++]

[BaekJoon] #8393 - 합 [Java][C++]

문제 링크


1. 아이디어

단순히 1부터 $n$까지 반복문으로 합을 구해도 되고, 1부터 $n$까지의 합 공식인 $\dfrac{n \cdot (n + 1)}{2}$을 활용해도 된다.


2. 복잡도

접근시간공간
반복 합산$O(N)$$O(1)$
등차수열 합 공식$O(1)$$O(1)$

($N$ = 입력값 n)


3. 코드

풀이 1: 반복 합산 [Java][C++]

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));

        int n = Integer.parseInt(br.readLine());

        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }

        System.out.println(sum);
    }
}
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(0);
    cin.tie(0);

    int n;
    cin >> n;

    int sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += i;
    }

    cout << sum;
}

풀이 2: 등차수열 합 공식 [Java][C++]

1
2
3
4
5
6
7
8
9
10
import java.io.*;

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

        int n = Integer.parseInt(br.readLine());
        System.out.println(n * (n + 1) / 2);
    }
}
1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;

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

    int n;
    cin >> n;
    cout << n * (n + 1) / 2;
}

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