[LeetCode] 204. Count Primes
Problem
Given an integer n
, return the number of prime numbers that are strictly less than n
.
Example 1:
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 0
Constraints:
0 <= n <= 5 * 10^6
Solution
class Solution {
public int countPrimes(int n) {
boolean[] notPrime = new boolean[n];
int count = 0;
for (int i = 2; i < n; i++) {
if (notPrime[i] == false)
count++;
for (int j = 2; i * j < n; j++)
notPrime[i * j] = true;
}
return count;
}
}
Explanation
- 소수를 찾는다면 다른 곱셈의 형태로는 불가능하고, 1과 숫자 본인의 곱셈으로 이루어진 수를 찾거나, 전체 수 중에서 여러 가지 곱셈 형태로 구성되는 수를 제외하면 된다. 본 문제는 후자의 방법으로 풀이를 해보았다.
- n미만의 숫자 중 소수의 곱셈 형태를 갖추지 못한 찾기 위해 boolean 타입의 배열 notPrime을 선언한다. 배열의 인덱스가 n미만의 수가 되고, 배열의 값이 소수의 곱셈형태를 만족하지 못하는지, 만족하는지를 나타낸다.
boolean[] notPrime = new boolean[n];
- for 반복문을 통해 소수의 곱셈 형태를 갖추지 못한 배열의 인덱스의 값을 true로 변경한다.
for (int i = 2; i < n; i++) { for (int j = 2; i * j < n; j++) notPrime[i * j] = true; }
- 소수의 개수를 나타내기 위하여 변수 count를 선언하고, 배열 notPrime의 값이 false를 나타내면 count값을 증가시키도록 한다.
int count = 0; for (int i = 2; i < n; i++) { if (notPrime[i] == false) count++; for (int j = 2; i * j < n; j++) notPrime[i * j] = true; }
- n미만의 수 중 소수를 나타내는 변수 count값을 반환한다.
return count;
Leave a comment