하루 한 접시

[백준] 4948번: 베르트랑 공준 [C#]

NaZZU 2024. 3. 31. 00:17

 

n부터 2n까지의 소수의 개수를 찾아서 출력해 주면 된다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System.IO;
using System.Text;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
 
namespace 연습장
{
    internal class Program
    {
        static void Main(string[] args)
        {
            using var reader = new StreamReader(Console.OpenStandardInput());
            using var print = new StreamWriter(Console.OpenStandardOutput());
            StringBuilder sb = new StringBuilder();
 
            while (true)
            {
                int input = int.Parse(reader.ReadLine());
                if (input == 0)
                    break;
                int cnt = 0;
 
                for (int i = input+1; i <= input * 2; i++)
                {
 
                    if (is_Prime(i))
                        cnt++;
                }
                sb.Append(cnt + "\n");
            }
            print.WriteLine(sb);
        }
 
        static bool is_Prime(int num)
        {
            if (num <= 1)
                return false;
 
            for (int i = 2; i <= Math.Sqrt(num); i++)
            {
                if (num % i == 0)
                    return false;
            }
 
            return true;
        }
    }
}
cs

 

전 문제와 별 차이가 없다. 문자열 문제에서 나오는 특정 값이 나오면 종료하는 부분만 차이가 있는 거 같음..