컴퓨터 사이언스/1고리즘
백준 1978 : 소수 찾기
저세상 개발자
2021. 9. 8. 10:38
https://www.acmicpc.net/problem/1978
백준에 질리도록 나오는 소수 문제다.
O(Nlog(logN))의 시간복잡도를 갖는 에라토스테네스의 체를 사용해서 문제를 해결하자.
#include <iostream>
using namespace std;
bool not_prime[1001];
void sieve(int range) {
not_prime[0] = 1, not_prime[1] = 1;
for (int i = 2; i * i <= range; i++) {
if (not_prime[i]) continue;
for (int j = i * 2; j <= range; j += i) {
not_prime[j] = 1;
}
}
}
void solution() {
int n, tmp, ans = 0;
cin >> n;
sieve(1000);
for (int i = 0; i < n; i++) {
cin >> tmp;
if (!not_prime[tmp]) ++ans;
}
cout << ans;
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
solution();
return 0;
}
메모리: 2020 kb | 시간: 0 ms |