primes/sieve-of-eratosthenes.js

  1. (function (exports) {
  2. 'use strict';
  3. /**
  4. * Sieve of Eratosthenes.
  5. *
  6. * Simple, ancient algorithm for finding all prime numbers up to given limit.
  7. *
  8. * Returns list of primes up to specified limit.
  9. *
  10. * For example, for limit 10 it should return following list of primes:
  11. * [2, 3, 5, 7].
  12. *
  13. * @module primes/sieve-of-eratosthenes
  14. * @param {Number} limit - Algorithm will returns list of primes up to
  15. * specified limit.
  16. * @returns {Array} Will return list with all prime numbers up to provided.
  17. * limit.
  18. *
  19. * @example
  20. * var sieveOfEratosthenes =
  21. * require('path-to-algorithms/src/sieve-of-eratosthenes').sieveOfEratosthenes;
  22. *
  23. * console.log(sieveOfEratosthenes(12)); // [2, 3, 5, 7, 11]
  24. */
  25. exports.sieveOfEratosthenes = function (limit) {
  26. var sieve = [];
  27. var primes = [];
  28. var k;
  29. var l;
  30. sieve[1] = false;
  31. for (k = 2; k <= limit; k += 1) {
  32. sieve[k] = true;
  33. }
  34. for (k = 2; k * k <= limit; k += 1) {
  35. if (sieve[k] !== true) {
  36. continue;
  37. }
  38. for (l = k * k; l <= limit; l += k) {
  39. sieve[l] = false;
  40. }
  41. }
  42. sieve.forEach(function (value, key) {
  43. if (value) {
  44. this.push(key);
  45. }
  46. }, primes);
  47. return primes;
  48. };
  49. }(typeof exports === 'undefined' ? window : exports));