[#62][알고리즘] 소수 구하기 (에라토스테네스의 체)

백준 > 소수 구하기

문제 링크(https://www.acmicpc.net/problem/1929)

문제

M이상 N이하의 소수를 모두 출력하는 프로그램을 작성하시오.

입력

첫째 줄에 자연수 M과 N이 빈 칸을 사이에 두고 주어진다. (1≤M≤N≤1,000,000)

출력

한 줄에 하나씩, 증가하는 순서대로 소수를 출력한다.

예제 입력 

3 16

예제 출력 

3
5
7
11
13

C++풀이
#include <iostream>
#include <algorithm>
#define SIZE 1000000
using namespace std;
 
long long isNotPrime[SIZE] = {0};
 
void eratos() {
    for(int i = 2; i * i < SIZE; i++)
        if(!isNotPrime[i])
            for (int j = i * i; j < SIZE; j += i) {
                isNotPrime[j] = 1;
            }
    isNotPrime[1= 1;
}
int main() {
    long long a, b;
    scanf("%u %u"&a, &b);
 
    eratos();
    
    for (long long i = a; i <= b; i++) {
        if (!isNotPrime[i])
            printf("%d\n", i);
    }
    return 0;
}
cs


댓글

가장 많이 본 글