[JAVA 문제 풀이] 287. 소수 찾기

프로그래머스 (12921)
Stupefyee's avatar
May 29, 2025
[JAVA 문제 풀이] 287. 소수 찾기
notion image
 

내가 작성한 코드

class Solution { public int solution(int n) { int answer = 1; // 2는 소수이므로 미리 1로 시작 for (int i = 3; i <= n; i += 2) { boolean isPrime = true; int sqrt = (int)Math.sqrt(i); // 제곱근까지만 검사하면 충분 // 제곱근 이하의 수로 나누어 떨어지는지 검사 for (int j = 2; j <= sqrt; j++) { if (i % j == 0) { isPrime = false; break; } } if (isPrime) answer++; } return answer; } }
Share article

stupefyee