简体   繁体   中英

Javascript code to find prime numbers doesn't work

I run this function, which i triggered with a button, and it should be printing the prime numbers. Instead, it printed all the numbers that it checked. The user is supposed to enter a number(for example 100) and all the numbers lower than it will be checked if they are prime, and if they are, they will be printed.(i is the number that is being checked)

function findeprime(num) {
    for (i = 2; i < num; i++) {
        for (coun = 2; coun < i; coun++) {
            if (i % coun == 0) continue;
        }
        document.write(i + " is prime <br/>");
    }
}

What am i doing wrong???

Your continue is only breaking out of the inner loop. I'd recommend something like this

function findeprime(num) {
    var isPrime;
    for (var i = 2; i < num; i++) {
        isPrime = true;
        for (coun = 2; coun < i; coun++) {
            if (i % coun == 0) isPrime = false;
        }
        if (isPrime) document.write(i + " is prime <br/>");
    }
}

It seems like your continue statement is misplaced. It is affecting the inner loop while your code will work properly only if it affected the outer loop.

Since you can't have a continue statement affect an outer loop/block, try the following:

 function findeprime(num) { for (i = 2; i < num; i++) { var prime = true; for (coun = 2; coun < i; coun++) { if (i % coun == 0) { prime = false; break; } } if(prime) alert(i + " is prime"); } } findeprime(14); 

As already pointed out, your continue is breaking the script out of the wrong loop. You can alternatively label the loop you want to break out of:

 function findeprime(num) { checknum: for (i = 2; i < num; i++) { for (coun = 2; coun < i; coun++) { if(i % coun == 0) continue checknum; } document.write(i + " is prime <br/>"); } } findeprime(20); 

Apparently everyone already gave you the answer, however i´m gonna post an additional example, for knowledge purposes.

 Number.prototype.isPrime = function() { for (var i = 2; i < this; i++) { if (this % i == 0) { return false; } } return true; }; function findPrimes(num) { var results = []; for (var i = 2; i <= num; i++) { if (i.isPrime()) results.push(i); } return results; } var primes = findPrimes(1000); document.write(primes.join(', ')); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM