백준: 4134(다음 소수)

강지안·2023년 6월 10일
0

baekjoon

목록 보기
57/186

문제

코드

import java.io.*;
import java.util.ArrayList;

public class q4134 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int T = Integer.parseInt(br.readLine());
        ArrayList<Long> inputs = new ArrayList<>();

        for(int i=0; i<T; i++)
            inputs.add(Long.parseLong(br.readLine()));

        for(int i=0; i<T; i++) {
            long result = inputs.get(i);
            if(result == 0 || result == 1) result = 2;
            while(true) {
                if(isPrime(result)) break;
                result++;
            }
            bw.write(result+"\n");
        }
        bw.flush();
    }
    public static boolean isPrime(long n) {
        for(int i = 2; i<Math.sqrt(n)+1; i++)
            if(i != n && n % i == 0) return false;
        return true;
    }
}

학습

소수 판별 시 sqrt(n)보다 이하인 수만 비교해도 된다.
참고 : https://makedotworld.tistory.com/13

주의

0과 1은 소수가 아니다

0개의 댓글