NiXt
NiXt

Reputation: 61

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???

Upvotes: 1

Views: 105

Answers (4)

Romulo
Romulo

Reputation: 5114

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(', '));

Upvotes: 0

CollinD
CollinD

Reputation: 7573

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/>");
    }
}

Upvotes: 4

Joseph Marikle
Joseph Marikle

Reputation: 78540

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);

Upvotes: 1

Meir
Meir

Reputation: 14395

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);

Upvotes: 3

Related Questions