Count the prime numbers from 2 to 100 with simpler code than this

Posted by RufioLJ on Stack Overflow See other posts from Stack Overflow or by RufioLJ
Published on 2012-10-12T04:42:20Z Indexed on 2012/10/16 11:01 UTC
Read the original article Hit count: 336

Filed under:

It has to be with just functions, variables, loops, etc (Basic stuff). I'm having trouble coming up with the code from scratch from what I've I learned so far(Should be able to do it). Makes me really mad :/. If you could give me step by step to make sure I understand I'd really really appreciated. Thanks a bunch in advanced.

How could I get the same result with a simpler code than this one:

var primes=4; 
for (var counter = 2; counter <= 100; counter = counter + 1)
{
    var isPrime = 0;
    if(isPrime === 0){ 
        if(counter === 2){console.log(counter);} 
        else if(counter === 3){console.log(counter);} 
        else if(counter === 5){console.log(counter);} 
        else if(counter === 7){console.log(counter);} 
        else if(counter % 2 === 0){isPrime=0;} 
        else if(counter % 3 === 0){isPrime=0;} 
        else if(counter % 5 === 0){isPrime=0;} 
        else if(counter % 7 === 0){isPrime=0;}
        else {
            console.log(counter);
            primes = primes + 1;
        }
    }
}
console.log("Counted: "+primes+" primes");

© Stack Overflow or respective owner

Related posts about JavaScript