Skip to content

Commit b3eeb01

Browse files
committed
Sieve of Eratosthenes ES6 code added
1 parent 67e1b47 commit b3eeb01

File tree

5 files changed

+36
-4
lines changed

5 files changed

+36
-4
lines changed

Number Theory/GCD/es6/gcd.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/* Greatest Common Divisor (GCD) Finding in JavaScript */
1+
/* Greatest Common Divisor (GCD) Finding in JavaScript (ES6) */
22

33
const gcd = (a, b) => {
44
while (true) {

Number Theory/LCM/es6/lcm.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/* Least Commond Multiple (LCM) Finding in JavaScript */
1+
/* Least Commond Multiple (LCM) Finding in JavaScript (ES6) */
22
const gcd = require('./gcd');
33

44
/*
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/* Sieve of Eratosthenes implementation in JavaScript(ES6) */
2+
3+
// This function will return the list of Primes less than given 'limit'
4+
module.exports.sieve = (limit) => {
5+
//As we know only 'even' prime number is 2, we are marking each of the 'even' index as false
6+
const sieve = new Array(limit).fill(0).map((elem, index) => ((index % 2) === 1)); //if the index is odd return true, otherwise
7+
8+
sieve[1] = false;
9+
sieve[2] = true;
10+
11+
const sqrtLimit = Math.sqrt(limit);
12+
13+
for (var i=3; i<=sqrtLimit; i+=2) {
14+
if (sieve[i] === true) {
15+
for (var k=i*i; k<=limit; k+=i)
16+
sieve[k] = false;
17+
}
18+
}
19+
20+
const primes = [];
21+
sieve.forEach((value, key) => {
22+
if (value)
23+
primes.push(key);
24+
});
25+
26+
return primes;
27+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
const { sieve } = require('./sieve');
2+
3+
/************ Testing Sieve of Eratosthenes Code ***************/
4+
console.log(sieve(100));

Number Theory/Sieve of Eratosthenes/sieve.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
/* Sieve of Eratosthenes implementation in JavaScript */
22

3+
// This function will return the list of Primes less than given 'limit'
34
function sieve(limit) {
4-
var sieve = [],
5-
primes = [];
65

76
var sieve = Array.apply(null, Array(limit)).map(function (elem, index) {
87
//As we know only 'even' prime number is 2, we are marking each of the 'even' index as false
@@ -21,6 +20,8 @@ function sieve(limit) {
2120
}
2221
}
2322

23+
var primes = [];
24+
2425
sieve.forEach(function (value, key) {
2526
if (value)
2627
primes.push(key);

0 commit comments

Comments
 (0)