[1929] 소수 구하기

RudinP·2023년 4월 12일
0

BaekJoon

목록 보기
40/77

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

입력

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

출력

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

생각

이전 소수 문제와 동일하게 풀이할 것이다. (소수 판별 제곱근 대칭성)
여기에서는 int형을 써도 무방.
에라토스테네스의 체는, 소수의 배수는 자기자신 제외 모두 소수가 아니라는 것을 이용하여 수를 제외해나가는 방법이다. 이 방법으로는 풀지 않지만, 알아두는 것이 좋을 듯 하다.

처음 코드

namespace SongE
{
    public class Program
    {
        static bool IsPrime(int x)
        {
            if (x <= 1)
            {
                return false;
            }

            if (x == 2) return true;

            for (int i = 2; i < Math.Sqrt(x) + 1; i++)
            {
                if (x % i == 0)
                    return false;
            }
            return true;
        }
        static void Main(string[] args)
        {
            using var input = new System.IO.StreamReader(Console.OpenStandardInput());
            using var print = new System.IO.StreamWriter(Console.OpenStandardOutput());

            int[] mn = Array.ConvertAll(input.ReadLine().Split(), s => int.Parse(s));

            for (int n = mn[0]; n < mn[1]; n++)
            {

                if (n <= 1) n++;

                if (IsPrime(n))
                {
                    print.WriteLine(n);
                }

            }
        }
    }
}

틀렸당.
보니까 for문에 n<mn[1]이라 써둠... n<=mn[1]로 고침.

두번째 코드

namespace SongE
{
    public class Program
    {
        static bool IsPrime(int x)
        {
            if (x <= 1)
            {
                return false;
            }

            if (x == 2) return true;

            for (int i = 2; i < Math.Sqrt(x) + 1; i++)
            {
                if (x % i == 0)
                    return false;
            }
            return true;
        }
        static void Main(string[] args)
        {
            using var input = new System.IO.StreamReader(Console.OpenStandardInput());
            using var print = new System.IO.StreamWriter(Console.OpenStandardOutput());

            int[] mn = Array.ConvertAll(input.ReadLine().Split(), s => int.Parse(s));

            for (int n = mn[0]; n <= mn[1]; n++)
            {

                if (n <= 1) n++;

                if (IsPrime(n))
                {
                    print.WriteLine(n);
                }

            }
        }
    }
}

profile
곰을 좋아합니다. <a href = "https://github.com/RudinP">github</a>

0개의 댓글