The first method of the Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to N.
The Sieve of Eratosthenes uses an extra O (n) memory and their runtime complexity is O (n log log n )
Creates a Boolean array of length = N IsPrime, with each element initialized to true;
K = 2: (n-1), if the current number k is the prime, put K^k-(n-1)/k *k of the number of pairs of mappings = false;
Finally, count from 2 to n-1 IsPrime = = True.
Code:
public class Solution {
public int countprimes (int n) {
boolean[] Isprimes = new Boolean[n];
for (int i = 0; i < isprimes.length; i++) {
Isprimes[i] = true;
}
for (int k = 2; k <= (n-1)/k; k++) {
if (isprimes[k] = = True) {
for (int i = k; I <= (n-1)/k; i++) {
Isprimes[i*k] = false;
}
}
}
int count = 0;
for (int i = 2; i< isprimes.length; i++) {
if (isprimes[i] = = true) count++;
}
return count;
}
}
You can also use DP to solve.
public class Solution {
public int countprimes (int n) {
int count = 0;
int squareroot = 1;
int number = 2;
list<integer> list = new arraylist<> ();
for (int i = number; i < n; i++) {
Boolean isprime = true;
if (SquareRoot * SquareRoot < i) squareroot++;
for (int j = 0; J < list.size () && List.get (j) <= squareroot;j++) {
if (I%list.get (j) = = 0) {
IsPrime = false;
Break
}
}
if (IsPrime = = True) {
List.add (i);
count++;
}
}
return count;
}
}
Runtime:o (N*SQRT (n)/log (n))
Finally, record the most primitive method of 0-sqrt (n):
public class Solution {
public int countprimes (int n) {
int count = 0;
int squareroot = 1;
int number = 2;
for (int i = number; i < n; i++) {
Boolean isprime = true;
for (int divisor = 2; divisor <= (int) (MATH.SQRT (i)); divisor++) {
if (I%divisor = = 0) {
IsPrime = false;
Break
}
}
if (IsPrime = = True) {
count++;
}
}
return count;
}
}
Jan 09-count Primes; Mathematics; optimization; Primes; DP;