1

here is what I have done so far:

window.onload = function() {
    var prime = false;
    for (var counter = 0; counter < 1000; counter++) {
        for (var i = 2; i <= counter; i++){
            if (counter % i == 0 && i != counter){
                prime = true;
            }
        }
            if (prime == false){
            document.write(counter);
        }
    }
};

This does not give me what I need at all, but I'm not too sure what I am doing wrong. I need to do some stuff with the prime numbers, but right now my issue is getting the prime numbers themselves. Thank you.

son rohan
  • 92
  • 1
  • 8
  • 1
    A simple google search will show you all sorts of algorithms in javascript for calculating primes. This is not something you need to invent yourself. – jfriend00 Oct 13 '14 at 21:51
  • try reinitializing prime boolean when the counter starts. Also to check wether it is a prime or not, you don't have to check till counter, but rather till Math.sqrt(counter). Also, your prime boolean seems to do the opposite, nl is it divisable instead of is it a prime nr. – Icepickle Oct 13 '14 at 21:53
  • You will also find that you need to set `prime=false` right between the two `for` statements. – jfriend00 Oct 13 '14 at 21:53

3 Answers3

0

You have it all messed up ...

  • if it's divisable,you say prime is true, and then you print out if prime is false?
  • i doesn't need to go up to counter, to it's root is enough.
  • where do you reset your prime variable? (hint, you don't)
Noctis
  • 11,507
  • 3
  • 43
  • 82
0

Here is a couple of placers to go for inspiration:

How to find prime numbers between 0 - 100?

http://nullman.net/project/JavascriptPrimeNumbers.html

Community
  • 1
  • 1
Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68
0

Answer can be found here. Found by simple Google search.

To quote:

Here's an example of a sieve implementation in JavaScript:

function getPrimes(max) {
    var sieve = [], i, j, primes = [];
    for (i = 2; i <= max; ++i) {
        if (!sieve[i]) {
            // i has not been marked -- it is prime
            primes.push(i);
            for (j = i << 1; j <= max; j += i) {
                sieve[j] = true;
            }
        }
    }
    return primes;
}

Then getPrimes(100) will return an array of all primes between 2 and 100 (inclusive). Of course, due to memory constraints, you can't use this with large arguments.

A Java implementation would look very similar.

Community
  • 1
  • 1
Matt DeKok
  • 197
  • 1
  • 8