[백준] 2231번 - 분해합 [Java][C++]
[백준] 2231번 - 분해합 [Java][C++]
1. 문제 풀이
자연수 $N$ 에 대한 가장 작은 생성자를 구하는 문제로 생성자는 해당 숫자와 각 자릿수의 합이 $N$ 이 되는 수들이다. $1$ 부터 $N$ 까지 모든 자연수에 대해 순서대로 분해합을 구해서 $N$ 이 되는지 비교해보는 브루트 포스로 간단하게 해결할 수 있다.
2. 코드
1. 브루트 포스 [Java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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());
for (int i = 1; i <= N; i++) {
int num = i;
int sum = num;
while (num > 0) {
sum += num % 10;
num /= 10;
}
if (sum == N) {
System.out.println(i);
return;
}
}
System.out.println(0);
}
}
2. 브루트 포스 [C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
int x = i;
int sum = x;
while (x > 0) {
sum += x % 10;
x /= 10;
}
if (sum == n) {
cout << i;
return 0;
}
}
cout << 0;
}
3. 풀이 정보
1. 브루트 포스 [Java]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| Java 11 | 124 ms | 14300 KB | 586 B |
2. 브루트 포스 [C++]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| C++ 17 | 8 ms | 2020 KB | 403 B |
This post is licensed under CC BY 4.0 by the author.