
난이도: ★★☆☆☆ • solved on: 2026-01-03

n 이상에서 가장 작은 소수를 찾아 출력해야 한다.자료구조
StringBuilder : 여러 줄 출력 누적BufferedReader : 빠른 입력알고리즘/기법
n부터 1씩 증가시키며 첫 소수 탐색핵심 키워드
- 문제 분해
- 각 입력
target에 대해current = target으로 시작한다.current가 소수인지 확인하고, 아니면current++하며 반복한다.- 처음으로 소수 판정을 통과한
current를 출력한다.
핵심 로직 흐름
for i in 1..T: current = target while true: if isPrime(current): print current break current++예외 처리
0,1은 소수가 아니므로false로 처리한다.2는 소수이므로true로 처리한다.
import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
long target;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < n; i++){
String s = br.readLine();
target = Long.parseLong(s);
long current = target;
while(true){
if(isPrime(current)){
sb.append(current).append("\n");
break;
}
current++;
}
}
System.out.print(sb);
}
public static boolean isPrime(long n){
if(n == 1 || n == 0) return false;
if(n == 2) return true;
for(long i = 2; i*i <= n; i++){
if(n % i == 0){
return false;
}
}
return true;
}
}
시간 복잡도: 최악의 경우 O(K × √M)
K = 소수를 찾을 때까지 증가한 횟수M = 검사 중인 수 크기공간 복잡도: O(1) (입력/출력 버퍼 제외)
0, 1이 소수가 아니라는 예외를 놓치면 오답이 나기 쉽다.target부터 시작해서 다음 소수를 찾는 반복 구조에서, 소수 판정 함수가 정확해야 한다.2부터 √n까지만 나눠보면 된다.비슷한 유형 (GPT 추천):
확장 문제 (GPT 추천):