모든 일상

[C# / 백준] 2581번 문제 소수 본문

코딩 공부/C#

[C# / 백준] 2581번 문제 소수

통통푸린 2023. 6. 1. 16:52
728x90
반응형
문제

자연수 M과 N이 주어질 때 M이상 N이하의 자연수 중 소수인 것을 모두 골라 이들 소수의 합과 최솟값을 찾는 프로그램을 작성하시오.

예를 들어 M=60, N=100인 경우 60이상 100이하의 자연수 중 소수는 61, 67, 71, 73, 79, 83, 89, 97 총 8개가 있으므로, 이들 소수의 합은 620이고, 최솟값은 61이 된다.

입력

입력의 첫째 줄에 M이, 둘째 줄에 N이 주어진다.

M과 N은 10,000이하의 자연수이며, M은 N보다 작거나 같다.

출력

M이상 N이하의 자연수 중 소수인 것을 모두 찾아 첫째 줄에 그 합을, 둘째 줄에 그 중 최솟값을 출력한다.

단, M이상 N이하의 자연수 중 소수가 없을 경우는 첫째 줄에 -1을 출력한다.

예제 입력 및 출력

풀이
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        private static void Main(string[] args)
        {
            int num1 = int.Parse(Console.ReadLine());
            int num2 = int.Parse(Console.ReadLine());
            int num_add = 0;

            List<int> result = new List<int>();
            for (int i = num1; i<=num2; i++)
            {
                List<int> list = new List<int>();

                for (int j = 1; j <= Math.Sqrt(i); j++)
                {
                    if (i % j == 0)
                    {
                        list.Add(j);
                    }
                }
                int cnt = list.Count;

                for (int j = 0; j < cnt; j++)
                {
                    list.Add(i / list[j]);
                }

                list = list.Distinct().ToList();
                list.Sort();

                if (list.Count == 2)
                {
                    num_add += list[1];
                    result.Add(list[1]);
                }
                result.Sort();

            }
            if(num_add != 0)
            {
                Console.WriteLine(num_add);
                Console.WriteLine(result[0]);
            }
            else
            {
                Console.WriteLine("-1");
            }
            
            
        }
    }
}
728x90
반응형