-
Notifications
You must be signed in to change notification settings - Fork 13
/
AmountOfPrimeNumbers.java
83 lines (71 loc) · 2.16 KB
/
AmountOfPrimeNumbers.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package by.andd3dfx.numeric;
import java.util.Arrays;
import java.util.BitSet;
/**
* Find amount of prime numbers which less than definite number N.
* <p>
* See <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Eratosthenes</a>
*
* @see <a href="https://youtu.be/VWP8mvmDRNc">Video solution</a>
*/
public class AmountOfPrimeNumbers {
public static int determine_usingPrimeDividersOfNumberSolution(int n) {
int result = 0;
for (int i = 2; i < n; i++) {
if (isPrime(i)) {
result++;
}
}
return result;
}
private static boolean isPrime(int number) {
return PrimeDividersOfNumber.determine(number).length == 1;
}
public static int determine_usingCustomIsPrimeWithEarlyReturn(int n) {
int result = 0;
for (int i = 2; i < n; i++) {
if (isPrimeEnhanced(i)) {
result++;
}
}
return result;
}
private static boolean isPrimeEnhanced(int number) {
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
public static int determine_usingEratosthenesSieve(int n) {
var isPrime = new boolean[n];
Arrays.fill(isPrime, 2, n, true);
for (var i = 2; i < n; i++) {
if (isPrime[i]) {
for (var j = 2; j * i < n; j++) {
isPrime[i * j] = false;
}
}
}
int result = 0;
for (var item : isPrime) {
if (item) {
result++;
}
}
return result;
}
public static int determine_usingEratosthenesSieveWithBitSet(int n) {
var isPrime = new BitSet(n);
isPrime.set(2, n);
for (var i = 2; i < n; i++) {
if (isPrime.get(i)) {
for (var j = 2; j * i < n; j++) {
isPrime.clear(i * j);
}
}
}
return isPrime.cardinality();
}
}