알고리즘 문제풀이/백준

[백준 1929] 소수 구하기

m2162003 2020. 12. 22. 22:43

www.acmicpc.net/problem/1929

 

1929번: 소수 구하기

첫째 줄에 자연수 M과 N이 빈 칸을 사이에 두고 주어진다. (1 ≤ M ≤ N ≤ 1,000,000) M이상 N이하의 소수가 하나 이상 있는 입력만 주어진다.

www.acmicpc.net

에라토스테네스의 체를 사용하여 구하면 쉽게 구한다.

#include <stdio.h>

using namespace std;

int m, n;

bool arr[1000001] = {
    false,
};

void eratos(int len)
{
  arr[1] = true;
  for (int i = 2; i <= len; i++)
  {
    if (arr[i] == true)
      continue;
    for (int j = 2; i * j <= len; j++)
    {
      arr[i * j] = true;
    }
  }
}
int main(void)
{
  scanf("%d %d", &m, &n);

  eratos(n);

  for (int i = m; i <= n; i++)
  {
    if (arr[i])
      continue;

    printf("%d\n", i);
  }
  return 0;
}