Skip to content

Commit 75f6d51

Browse files
committed
added "Sieve of Eratosthenes" - Simple, ancient algorithm for finding all prime numbers up to any given limit
1 parent 9c6b1d8 commit 75f6d51

4 files changed

Lines changed: 70 additions & 2 deletions

File tree

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
node_modules
22
npm-debug.log
3-
debug
3+
debug
4+
.idea

gulpfile.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ var gulp = require('gulp'),
66
stylish = require('jshint-stylish');
77

88
gulp.task('jsdoc', shell.task([
9-
'./node_modules/.bin/jsdoc -c ./doc-config.json',
9+
'./node_modules/.bin/jsdoc -c ./doc-config.json'
1010
]));
1111

1212
gulp.task('lint', function () {
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Sieve of Eratosthenes
3+
*
4+
* Simple, ancient algorithm for finding all prime numbers up to any given limit
5+
*/
6+
(function (exports) {
7+
'use strict';
8+
9+
/**
10+
* Returns Sieve of Eratosthenes for specified number
11+
*
12+
* Simple, ancient algorithm for finding all prime numbers up to any given
13+
* limit
14+
*
15+
* @param {Number} limit - algorithm will return list with prime numbers up
16+
* to given limit
17+
*
18+
* @returns {Array} - will return array with all prime numbers up to
19+
* provided limit
20+
*/
21+
exports.sieveOfEratosthenes = function (limit) {
22+
var sieve = [],
23+
primes = [], k, l;
24+
25+
sieve[1] = false;
26+
27+
for (k = 2; k <= limit; k += 1) {
28+
sieve[k] = true;
29+
}
30+
31+
for (k = 2; k * k <= limit; k += 1) {
32+
if (sieve[k] !== true) {
33+
continue;
34+
}
35+
36+
for (l = k * k; l <= limit; l += k) {
37+
sieve[l] = false;
38+
}
39+
}
40+
41+
sieve.forEach(function (value, key) {
42+
if (value) {
43+
this.push(key);
44+
}
45+
}, primes);
46+
47+
return primes;
48+
};
49+
50+
}(typeof exports === 'undefined' ? window : exports));
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
'use strict';
2+
3+
var sieveOfEratosthenes =
4+
require('../../src/primes/sieve-of-eratosthenes').sieveOfEratosthenes;
5+
6+
describe('Sieve Of Eratosthenes', function () {
7+
it('should give the right sequence of primes for limit 12', function () {
8+
expect(sieveOfEratosthenes(12).toString())
9+
.toBe([2, 3, 5, 7, 11].toString());
10+
});
11+
12+
it('should give the empty list for limit less or equal 1', function () {
13+
expect(sieveOfEratosthenes(-12).toString()).toBe([].toString());
14+
expect(sieveOfEratosthenes(0).toString()).toBe([].toString());
15+
expect(sieveOfEratosthenes(1).toString()).toBe([].toString());
16+
});
17+
});

0 commit comments

Comments
 (0)