BaekJoon[C#]

기본 수학 2단계 2581

wny0320 2022. 10. 29. 21:54

백준 온라인 코딩 문제풀이

https://www.acmicpc.net/

 

Baekjoon Online Judge

Baekjoon Online Judge 프로그래밍 문제를 풀고 온라인으로 채점받을 수 있는 곳입니다.

www.acmicpc.net

 

코드 참고

https://replit.com/@wny0320

 

wny0320 (박 상운)

Run code live in your browser. Write and run code in 50+ languages online with Replit, a powerful IDE, compiler, & interpreter.

replit.com

 

2581에 대해 다룸

 


2581

using System;
class Program
{
    static void Main(string[] args)
    {
        int a = int.Parse(Console.ReadLine());
        int b = int.Parse(Console.ReadLine());
        int result = 0;
        int min = 0;
        for(int i = a; i <= b; i++)
        {
            int cnt = 0;
            for (int j = 2; j < i; j++)
            {
                if (i % j == 0)
                {
                    cnt++;
                    break;
                }
            }
            if(i == 1)
            {

            }
            else if (i == 2)
            {
                min = 2;
                result += 2;
            }
            else if(cnt == 0)
            {
                if (result == 0)
                {
                    min = i;
                }
                result += i;
            }
        }
        if(result == 0)
        {
            Console.WriteLine(-1);
        }
        else
        {
            Console.WriteLine(result);
            Console.WriteLine(min);
        }
    }
}

전에 풀은 문제랑 비슷함

 

for문을 돌릴 범위를 받은 후 돌려서 나눠지면 cnt++과 break를 걸음

 

i가 1일때는 넘기고 2일때는 최소값과 result 값을 더해주고

 

나머지는 result에 i를 더해주는데 result가 0이라면 처음 들어가는 제일 작은 소수이기 때문에 min에 i를 대입

 

이후 reuslt 가 0이면 -1을 출력 아니라면 result와 min을 출력

'BaekJoon[C#]' 카테고리의 다른 글

기본 수학 2단계 1929  (0) 2022.10.31
기본 수학 2단계 11653  (0) 2022.10.30
기본 수학 2단계 1978  (0) 2022.10.28
기본 수학 1단계 10757  (0) 2022.10.21
기본 수학 1단계 2839  (0) 2022.10.20