Skip to content

Commit d734d14

Browse files
author
Wakidur Rahaman
committed
allPrimesLessThanN
1 parent a3ed323 commit d734d14

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,59 @@
1+
/**
2+
* 1.
3+
* Given three numbers x, y, and p, compute (xˆy) % p. (This is modular exponentiation.)
4+
* Here, x is the base, y is exponent, and p is the modulus.
5+
* Modular exponentiation is a type of exponentiation performed over a modulus,
6+
* which is useful in computer science and used in the field of public-key encryption algorithms
7+
*
8+
* @param base
9+
* @param exponent
10+
* @param modulus
11+
* @returns
12+
*/
113
function modularExponentiation(base: number, exponent: number, modulus: number): number {
214
return Math.pow(base, exponent) % modulus;
315
}
16+
17+
function modularExponentiation01(base: number, exponent: number, modulus: number): number {
18+
if (modulus == 1) return 0;
19+
20+
let value = 1;
21+
22+
for (let i = 0; i < exponent; i++) {
23+
value = (value * base) % modulus;
24+
}
25+
26+
return value;
27+
}
28+
29+
/**
30+
* 2.
31+
* Print all primes lass than n.
32+
*
33+
* Simply iterate from 0 to n and print any prime numbers where isPrime() evaluates to true.
34+
*
35+
*/
36+
37+
function allPrimesLessThanN(n: number): void {
38+
for (let i = 0; i < n; i++) {
39+
if (isPrimeNumber(i)) {
40+
console.log(i);
41+
}
42+
}
43+
} // time complexity of O(n sqrt(n)) is run n times.
44+
45+
function isPrimeNumber(number: number): boolean {
46+
if (number <= 1) return false;
47+
if (number <= 3) return true;
48+
49+
// This is checked so that we can skip
50+
// middle five number in below loop
51+
52+
for (let i = 5; i * i < number; i = i + 6) {
53+
if (number % i == 0 || number % (i + 2) == 0) {
54+
return false;
55+
}
56+
}
57+
58+
return true;
59+
} // time complexity of O(sqrt(n)) is run n times.

0 commit comments

Comments
 (0)