[백준 | 2581번] 소수

728x90
https://www.acmicpc.net/problem/2581

📝 나의풀이

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		int N = scanner.nextInt(); 
		int M = scanner.nextInt(); 
		
		
		int sum =0;
		List<Integer> numberList = new ArrayList<>();
		
		for(int i=N; i<=M; i++) {
			
			boolean num = true;
			
			if(i==1) {
				continue;
			}
			
			for(int j=2; j<=Math.sqrt(i); j++) {
				if(i%j==0) {
					num=false;
					break;
				}
			}
			
			
			if(num) {
				sum+=i;
				numberList.add(i);
			}
		}
	
		if(numberList.isEmpty()) {
			System.out.println("-1");
		} else {
			System.out.println(sum);
			System.out.println(numberList.get(0));
		}
	}
}
  • arrayList에 담아야지! 하고 봤는데 for문에서 꽉 막혀서 다른 풀이들을 참고했다.(boolean 사용)
  • 1은 소수가 아니기 때문에 continue 처리
  • for문으로 2 ~ Math.sqrt(i) 까지 돌려보았을 때 나누어 떨어지는 값이 있는 경우 false 처리 (소수X)
    그 외 숫자 (소수인 경우)만 sum과 numberList에 더해준다.
  • 만약, numberList가 비어있는 경우 "-1"을 출력하고
    비어있지 않은 경우 합계와 numberList의 0번째 값을 가져온다.
    (어차피 순서대로 담기기 때문에 정렬을 따로 하지 않았다.)
728x90