To counter the number of Prime number between 1 - n.
The mainly is to delete the number and its multiple.
Problem in AcWing
Simply code
The time complexity is the O(nlogn) (Harmonic series)
We need to optimization.
Egyptian Filtering
The time complexity will be O(n loglogn)
Only delete the prime number in 1 - n.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static int N = 1000010;
static int prime[] = new int[N], cnt;
static boolean st[] = new boolean[N];
public static void main(String[] args) throws IOException {
String[] s = br.readLine().split(" ");
int n = Integer.parseInt(s[0]);
f(n);
pw.println(cnt);
pw.flush();
br.close();
}
private static void f(int n) {
for (int i = 2; i <= n; i++) {
if (!st[i]) {
cnt++;
for (int j = (i << 1); j <= n; j += i) st[j] = true;
}
}
}
}
Linear Filtering
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static int N = 1000010;
static int prime[] = new int[N], cnt;
static boolean st[] = new boolean[N];
public static void main(String[] args) throws IOException {
String[] s = br.readLine().split(" ");
int n = Integer.parseInt(s[0]);
f(n);
pw.println(cnt);
pw.flush();
br.close();
}
private static void f(int n) {
for (int i = 2; i <= n; i++) {
if (!st[i]) prime[cnt++] = i;
for (int j = 0; prime[j] <= n / i; j++) {
st[prime[j] * i] = true;
if (i % prime[j] == 0) break;
}
}
}
}
When i % prime[j] == 0 then prime[j] must be the minimal prime factor of prime[j] * i.