Skip to content

Commit 21019af

Browse files
solves count primes
1 parent 4ee67d2 commit 21019af

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@
6262
| 198 | [House Robber](https://leetcode.com/problems/house-robber) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/HouseRobber.java) |
6363
| 202 | [Happy Number](https://leetcode.com/problems/happy-number) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/HappyNumber.java) |
6464
| 203 | [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/RemoveLinkedListElements.java) |
65-
| 204 | [Count Primes](https://leetcode.com/problems/count-primes) | Easy |
65+
| 204 | [Count Primes](https://leetcode.com/problems/count-primes) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)]() |
6666
| 205 | [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings) | Easy |
6767
| 206 | [Reverse Linked Lists](https://leetcode.com/problems/reverse-linked-list) | Easy |
6868
| 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate) | Easy |

Diff for: src/CountPrimes.java

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
public class CountPrimes {
2+
3+
public static int countPrimes(int number) {
4+
boolean[] sieve = getSieve(number);
5+
return numberOfPrimes(sieve);
6+
}
7+
8+
private static int numberOfPrimes(boolean[] array) {
9+
int count = 0;
10+
for (boolean value : array) {
11+
if (!value) count++;
12+
}
13+
return count;
14+
}
15+
16+
private static boolean[] getSieve(int number) {
17+
if (number < 2) {
18+
return new boolean[0];
19+
}
20+
21+
boolean[] sieve = new boolean[number];
22+
sieve[0] = sieve[1] = true;
23+
for (long index = 2 ; index < sieve.length ; index++){
24+
if (!sieve[(int) index]) {
25+
for (long j = index * index ; j < sieve.length ; j += index) {
26+
sieve[(int) j] = true;
27+
}
28+
}
29+
}
30+
31+
return sieve;
32+
}
33+
}

0 commit comments

Comments
 (0)