Skip to content

Commit 6497fda

Browse files
author
Wakidur Rahaman
committed
Number Algorithms
1 parent 926feba commit 6497fda

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/problems/isPrime-01.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
*
3+
* Number Algorithms
4+
* One of the most discussed algorithms involving numbers is for testing whether a number is a prime number..
5+
* @returns
6+
*/
7+
// A primality test can be done by iterating from 2 to n, checking whether modulus division (remainder) is equal to zero.
8+
function isPrimeOne(n: number) {
9+
if (n <= 1) {
10+
return false;
11+
}
12+
13+
// check from 2 to n - 1;
14+
for (let i = 2; i < n; i++) {
15+
if (n % i == 0) {
16+
return false;
17+
}
18+
}
19+
20+
return true;
21+
} // Time complexity: O(n)
22+
23+
function isPrimeTwo(n: number) {
24+
if (n <= 1) return false;
25+
if (n <= 3) return true;
26+
27+
// This is checked so that we can skip
28+
// Middle five numbers in below loop
29+
30+
if (n % 2 == 0 || n % 3 == 0) return false;
31+
32+
for (let i = 5; i * i <= n; i = i + 6) {
33+
if (n % i == 0 || n % (i + 2) == 0) return false;
34+
}
35+
return true;
36+
} // O(sqrt(n))

0 commit comments

Comments
 (0)