mshwf
mshwf

Reputation: 7459

Writing JavaScript function that generate prime numbers, why are some numbers excluded from the loop?

I wrote this function that generates prime numbers for a given range of numbers, I think it's simple and clear that must give the expected result, though, there are numbers that are excluded from the result:

function numberator(from, to) {
    numbers = [];
    for (x = from; x <= to; x++) {
        numbers.push(x);
    }
    return numbers;
}

function primeNumbers(array) {
    for (i = 0; i < array.length; i++) {
        for (j = 2; j < array[i]; j++) {
            if (array[i] % j == 0) {
                array.splice(i, 1);
            }
        }
    }
    return array;
}

console.log(primeNumbers(numberator(1,100)));

The result contains: 27, 35 and 95 (also 1, that I may handle later.)

I tried to figure out why but I couldn't.

Upvotes: 0

Views: 789

Answers (4)

hmaxf2
hmaxf2

Reputation: 656

Just want to share a simple and very easy to understand Javascript code to generate small prime numbers: https://github.com/HMaxF/generate-small-prime-number

Upvotes: 0

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93451

Take it more simple :

const isPrime = (n =>
        n>1 && 
        Array.from({length: Math.floor(Math.sqrt(n))-1},(e,i) => i+2)
             .every(m => n%m)
);

const generateRange = (from, to) => Array.from({length: to-from + 1}, (v, k) => k+from);

then

generateRange(1, 100).filter(isPrime); // DONE!

//---- Utilities 
const isPrime = (n =>
        n>1 && 
        Array.from({length: Math.floor(Math.sqrt(n))-1},(e,i) => i+2)
             .every(m => n%m)
);

 const generateRange = (from, to) => Array.from({length: to-from + 1}, (v, k) => k+from);

//---------Apply ---
const from = 1;
const to = 100; 

 console.log (
    `Prime numbers from ${from} to ${to} are : `,
    generateRange(from, to).filter(isPrime)
  )

Upvotes: -1

tewathia
tewathia

Reputation: 7328

In this

array.splice(i, 1);

statement you are changing the length of the array but not modifying the index i accordingly. Change it to

array.splice(i--, 1)

Upvotes: 1

Amit Kumar
Amit Kumar

Reputation: 1517

The bug is in-place modification of array with splice. You keep on incrementing i, while the size of array is getting modified at execution time.

You can debug this, by printing the whole array after each slice operation.

Also the solution is highly inefficient and will perform terribly for slightly long ranges. Use Sieve of Eratosthenes

Upvotes: 5

Related Questions