Advertisement
zidniryi

sieheve

Mar 11th, 2020
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. // @konsepkoding
  2. // Sieve of Eratosthenes in JS
  3.  
  4. // In mathematics, the Sieve of Eratosthenes is a simple and ingenious
  5. // ancient algorithm for finding all prime numbers up to any given limit.
  6.  
  7. var eratosthenes = function(n) {
  8. // Eratosthenes algorithm to find all primes under n
  9. var array = [], upperLimit = Math.sqrt(n), output = [];
  10.  
  11. // Make an array from 2 to (n - 1)
  12. for (var i = 0; i < n; i++) {
  13. array.push(true);
  14. }
  15.  
  16. // Remove multiples of primes starting from 2, 3, 5,...
  17. for (var i = 2; i <= upperLimit; i++) {
  18. if (array[i]) {
  19. for (var j = i * i; j < n; j += i) {
  20. array[j] = false;
  21. }
  22. }
  23. }
  24.  
  25. for (var i = 2; i < n; i++) {
  26. if(array[i]) {
  27. output.push(i);
  28. }
  29. }
  30.  
  31. return output;
  32. }
  33. // Max bumber
  34. var result = eratosthenes(15).join(", ")
  35. // Log The result
  36. console.log(result)
  37. // result : "2, 3, 5, 7, 11, 13"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement