Skip to content

Commit c8ca8b4

Browse files
Merge pull request #60 from wakidurrahman/feat/primality-test
Number Algorithms
2 parents 926feba + 55e0299 commit c8ca8b4

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

src/problems/isPrime-01.ts

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
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+
// Algorithm 01: A primality test can be done by iterating from 2 to n, checking whether modulus division (remainder) is equal to zero.
8+
// 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97
9+
function isPrimeOne(n: number) {
10+
if (n <= 1) {
11+
return false;
12+
}
13+
14+
// check from 2 to n - 1;
15+
for (let i = 2; i < n; i++) {
16+
if (n % i == 0) {
17+
return false;
18+
}
19+
}
20+
21+
return true;
22+
} // Time complexity: O(n)
23+
24+
function isPrimeTwo(n: number) {
25+
if (n <= 1) return false;
26+
if (n <= 3) return true;
27+
28+
// This is checked so that we can skip
29+
// Middle five numbers in below loop
30+
31+
if (n % 2 == 0 || n % 3 == 0) return false;
32+
33+
for (let i = 5; i * i <= n; i = i + 6) {
34+
if (n % i == 0 || n % (i + 2) == 0) return false;
35+
}
36+
return true;
37+
} // O(sqrt(n))
38+
39+
function primeFactors(n: number) {
40+
// Print the number of 2s that divide n
41+
while (n % 2 == 0) {
42+
console.log(2);
43+
n = n / 2;
44+
}
45+
46+
// n must be odd at this point. So we can skip one element
47+
// note i = i + 2;
48+
for (let i = 3; i * i <= n; i = i + 2) {
49+
// While i divides n, print i and divide n
50+
while (n % i == 0) {
51+
console.log(i);
52+
n = n / i;
53+
}
54+
}
55+
// This condition is to handle the case when n is a prime number greater than 2
56+
if (n > 2) {
57+
console.log(n);
58+
}
59+
} // O(sqrt(n))
60+
61+
// Random Number Generator
62+
Math.random() * 100; // floats between 0 and 100;
63+
Math.random() * 25 + 5; // floats between 5 and 30
64+
Math.random() * 10 - 100; // floats between -100 and -90

0 commit comments

Comments
 (0)