Post

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

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

문제 링크


1. 문제 풀이


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


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

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

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

        System.out.println(sum);
    }
}


2. 합 공식 [Java]

1
2
3
4
5
6
7
8
9
10
11
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);
    }
}


3. 단순 구현 [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);

    int n;
    cin >> n;

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

    cout << sum;
}


4. 합 공식 [C++]

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

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

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

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