File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ // A primality test can be done by iterating from 2 to n, checking whether modulus division (remainder) is equal to zero.
2
+ function isPrime ( n : number ) {
3
+ if ( n <= 1 ) {
4
+ return false ;
5
+ }
6
+
7
+ // check from 2 to n - 1;
8
+ for ( let i = 2 ; i < n ; i ++ ) {
9
+ if ( n % i == 0 ) {
10
+ return false ;
11
+ }
12
+ }
13
+
14
+ return true ;
15
+ } // Time complexity: O(n)
16
+
17
+ function isPrime01 ( n : number ) {
18
+ if ( n <= 1 ) return false ;
19
+ if ( n <= 3 ) return true ;
20
+
21
+ // This is checked so that we can skip
22
+ // Middle five numbers in below loop
23
+
24
+ if ( n % 2 == 0 || n % 3 == 0 ) return false ;
25
+
26
+ for ( let i = 5 ; i * i <= n ; i = i + 6 ) {
27
+ if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ;
28
+ }
29
+ return true ;
30
+ } // O(sqrt(n))
You can’t perform that action at this time.
0 commit comments