C, C++ Language/๐Ÿฅˆ BOJ

(C++) โ˜…Number Theory Intermediate I - 2 Solvedโ˜…

metamong 2024. 11. 15.

โ˜… 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๊นŒ์ง€์˜ ์†Œ์ˆ˜์˜ ๊ฐœ์ˆ˜ ๊ตฌํ•˜๊ธฐ


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

๋Œ“๊ธ€