728x90
https://www.acmicpc.net/problem/3896
3896번: 소수 사이 수열
문제 연속한 소수 p와 p+n이 있을 때, 그 사이에 있는 n-1개의 합성수(소수나 1이 아닌 양의 정수)는 길이가 n인 소수 사이 수열라고 부른다. 양의 정수 k가 주어졌을 때, k를 포함하는 소수 사이 수열의 길이를 구하는 프로그램을 작성하시오. k를 포함하는 소수 사이 수열이 없을 때는 길이가 0이다. 예를 들어, 소수 23과 29의 소수 사이 수열은 {24, 25, 26, 27, 28}이고, 길이는 6이다. 입력 첫째 줄에 테스트 케이스의 개수 T
www.acmicpc.net
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
bool arr[1299710] = { false };
int where[1299710] = { 0 };
int main() {
cin.tie(NULL);
ios_base::sync_with_stdio(false);
vector<int> primeNumber;
arr[1] = true;
for (int i = 2; i <= 1299709; i++) {
if (!arr[i]) {
primeNumber.push_back(i);
where[i] = primeNumber.size() - 1;
for (int j = 2; ; j++) {
if (j * i > 1299709) break;
arr[i * j] = true;
}
}
}
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int num;
cin >> num;
if (arr[num]) {
for (int j = num - 1; ; j--) {
if (!arr[j]) {
cout << primeNumber[where[j] + 1] - primeNumber[where[j]] << '\n';
break;
}
}
}
else cout << 0 << '\n';
}
return 0;
}
728x90
'알고리즘 문제' 카테고리의 다른 글
[백준] 11816번 8진수, 10진수, 16진수 (0) | 2020.03.03 |
---|---|
[백준] 2752번 세수정렬 (0) | 2020.03.03 |
[백준] 9020번 골드바흐의 추측 (0) | 2020.03.03 |
[백준] 5337번 웰컴 (0) | 2020.03.01 |
[백준] 1011번 Fly me to the Alpha Centauri (0) | 2020.03.01 |