Repository navigation
Expand file tree
/
Copy pathCountPrimes.java
More file actions
83 lines (61 loc) · 1.73 KB
/
Copy pathCountPrimes.java
File metadata and controls
83 lines (61 loc) · 1.73 KB
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
import java.util.Arrays;
import java.util.Scanner;
// 204. Count Primes
// https://leetcode.com/problems/count-primes/description/
public class CountPrimes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(countPrimes(n));
}
// BRUTEFORCE GETTING TLE NOT OPTIMISED SOLUTION
// public static int countPrimes(int n) {
// int mam = 0 ;
// int n1 = 0 ;
// while(n1 < n){
// if(isPrime(n1)){
// mam++;
// }
// n1++;
// }
// return mam ;
// }
// public static boolean isPrime(int n1){
// if(n1 < 2){
// return false ;
// }
// else{
// for(int i = 2 ; i <= Math.sqrt(n1) ; i++){
// if(n1 % i == 0){
// return false ;
// }
// }
// return true ;
// }
// }
// HERE IS THE SIEVE METHOD WHAT IT DO IS I HAVE LEARBED IT
// we know 2 is prime then multiple of 2 in range n will not be prime
// same goes with 3, 5, 7
public static int countPrimes(int n) {
if(n <= 2){
return 0 ;
}
boolean[] arr = new boolean[n];
Arrays.fill(arr,true);
arr[0] = arr[1] == false ;
for(int i = 2 ; i <= (int) Math.sqrt(n) ; i++){
if(arr[i]){
for(int j = i * i ; j < n ; j+=i){
arr[j] = false ;
}
}
}
int cou = 0 ;
for(int i = 2 ; i < arr.length ; i++){
if(arr[i]){
++cou;
}
}
return cou ;
}
}