numbers – Javascript + return PrimeNumbers

numbers – Javascript + return PrimeNumbers

25/Math.sqrt(25) = 0, therefore NotPrime

BUT 25/2=12.5, 25/3=8.3333 25/4=6.25 => IsPrime

No. Only because it neither is divisible by 2, 3, and 4, it does not mean that 25 is a prime number. It must be divisible by nothing (except 1 and itself) – but 25 is divisible by 5 as you noticed. You will have to check against that as well.

13 is printed twice because 13/2 and 13/3 is executed.

Question here: I would like to fix this duplication also?

Your logic is flawed. As above, just because a number is not divisible by an other number that does not mean it was prime – but your code prints results based on that condition. Instead, is has to be not divisible by all other numbers.

You just have an extra condition that nothing that is divisible by 2 or 3 enters the loop, but everything that is divisible by 5, 7, 11 etc (and not divisible by 2 or 3) is yielded. 25 is just the first number to occur in that series, the next ones will be 35 and 49.

Actually youre already testing 2 and 3 in the loop from 2 to a already, so you should just omit that condition. You wouldve noticed your actual problem much faster then if you had tried:

function prime(n) {
    for (var i = 1; i <= n; i++) {
        var a = Math.floor(Math.sqrt(i));
        for(j = 2; j<=a; j++) { 
            if(!isInt(i/j)) {
                console.log(i+/+j+==+i/j+, therefore +i+ is Prime);

The logic should be: Test all divisors from 2 to sqrt(i), and if i is divisible by any of them you know that its not a prime. Only if it has passed the loop with none of them being a factor of i, you know in the end that its a prime. Ill leave that as an exercise to you 🙂

numbers – Javascript + return PrimeNumbers

Leave a Reply

Your email address will not be published. Required fields are marked *