Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // @konsepkoding
- // Sieve of Eratosthenes in JS
- // In mathematics, the Sieve of Eratosthenes is a simple and ingenious
- // ancient algorithm for finding all prime numbers up to any given limit.
- var eratosthenes = function(n) {
- // Eratosthenes algorithm to find all primes under n
- var array = [], upperLimit = Math.sqrt(n), output = [];
- // Make an array from 2 to (n - 1)
- for (var i = 0; i < n; i++) {
- array.push(true);
- }
- // Remove multiples of primes starting from 2, 3, 5,...
- for (var i = 2; i <= upperLimit; i++) {
- if (array[i]) {
- for (var j = i * i; j < n; j += i) {
- array[j] = false;
- }
- }
- }
- for (var i = 2; i < n; i++) {
- if(array[i]) {
- output.push(i);
- }
- }
- return output;
- }
- // Max bumber
- var result = eratosthenes(15).join(", ")
- // Log The result
- console.log(result)
- // result : "2, 3, 5, 7, 11, 13"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement