[백준] 8393번 - 합 [Java][C++]
[백준] 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;
}
3. 풀이 정보
1. 구현 [Java]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| Java 11 | 108 ms | 14136 KB | 370 B |
2. 수학 [Java]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| Java 11 | 100 ms | 14100 KB | 289 B |
3. 구현 [C++]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| C++ 17 | 0 ms | 2020 KB | 238 B |
4. 수학 [C++]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| C++ 17 | 0 ms | 2020 KB | 172 B |
This post is licensed under CC BY 4.0 by the author.