โ 1929 ์์ ๊ตฌํ๊ธฐ โ

//1929
#include <iostream>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cmath>
#include <map>
#include <set>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int M, N;
cin >> M >> N;
vector <int>sieve(N+1, true);
for(int i=2;i<=(int)sqrt(N);i++){
if(sieve[i] == true){
int j = 2;
while(i*j<=N){
sieve[i*j] = false;
j+=1;
}
}
}
for(int i=M;i<=N;i++){
if (sieve[i] && i!=1){
cout << i << '\n';
}
}
return 0;
}
๐ณ๐ปโ๏ธ vector<int> sieve ๊ฐ๋ณ ๋ฐฐ์ด์ ๋ง๋ ๋ค. (N+1, true)๋ฅผ ๋ค์ ๋ถ์ด๋ฉด ์ด N+1๊ฐ์ ์๋ฆฌ๊ฐ ์๊ณ ๋ชจ๋ true๋ก initialization.
๐ณ๐ปโ๏ธ์์ฐ์ N๊น์ง์ ๋ชจ๋ ์์ ๊ตฌํ๊ธฐ (์๋ผํ ์คํ ๋ค์ค์ ์ฒด)
(1) 2๋ถํฐ root(N)๊น์ง ๋๋ฆฌ๊ธฐ
(2) ๋๋ฆฌ๋ฉฐ ํด๋น ๊ฐ sieve[i]๊ฐ true์ผ ๋, i๋ฅผ 2๋ฐฐ ์ด์ ๊ณฑํ ๊ฒฐ๊ณผ๋ถํฐ N๊น์ง์ ๋ชจ๋ i์ ๋ฐฐ์๋ฅผ false ์ฒ๋ฆฌ(๋ฐฐ์์ด๋ฏ๋ก ์์ x)
(3) ์ต์ข ์ ์ผ๋ก true์ธ ๊ฒ๋ง ์์(๋จ 0๊ณผ 1 ์ ์ธ)
โ 4948 ๋ฒ ๋ฅด๋ฅด๋ ๊ณต์ค โ

//4948
#include <iostream>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cmath>
#include <map>
#include <set>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, ans;
while(true){
cin >> n;
ans = 0;
if(n==0){
break;
}
vector<int> sieve(2*n+1,true);
sieve[0] = false;
sieve[1] = false;
//sieve of eratosthenes
for(int x=2;x<=(int)sqrt(2*n);x++){
if(sieve[x]){
int j = 2;
while(x*j<=2*n){
sieve[x*j] = false;
j += 1;
}
}
}
for(int i=n+1;i<=2*n;i++){
if(sieve[i]){
ans+=1;
}
}
cout << ans << endl;
}
return 0;
}
๐ณ๐ปโ๏ธ 2*n+1(0 ํฌํจ)๊ฐ์ ์ซ์๊ฐ ๋ค์ด๊ฐ ์ ์๋ sieve ์์ฑํด์ n+1๋ถํฐ 2*n๊น์ง์ ์์์ ๊ฐ์ ๊ตฌํ๊ธฐ
'C, C++ Language > ๐ฅ BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| (C++) โ Set/Map Upper-Intermediate I - 1 Solvedโ (0) | 2024.11.15 |
|---|---|
| (C++) โ Stack & Queue & Deque Intermediate I - 4 Solvedโ (0) | 2024.11.15 |
| (C++) โ Set/Map Intermediate I - 5 Solvedโ (2) | 2024.11.14 |
| (C++) โ Sorting Intermediate I - 5 Solvedโ (0) | 2024.11.14 |
| (C++)โ BF Intermediate I - 1 Solvedโ (0) | 2024.11.14 |
๋๊ธ