[Javascript] Generating Prime Numbers

Steve Vernon steve at extremewattage.co.uk
Mon Jan 6 05:52:03 CST 2003


You mean from one to 100? If you alter from for (i=2; i<=100; i++) to for
(i=2; i<=2000; i++) it will owrk up to 2000.

It starts with a loop from 2 to 100. The first check outputs a new line for
basically multiples of 100.

% is the remainer (modulos) operator, 3%3 = 0, 3%2 = 1 as is the remainder
if youy take one multiple of 2 off. Basically it returns however many of the
second item fits in the second, and returns the difference. E.g. 103%2, so
50 2's fit into 100. And this leaves 3.

The next bit checks every number under this number to see if it divides into
the number. A prime can only be devided by itself and 1. So even numbers are
NEVER prime numbers as they divide by 2 to give a whole number. If the
number divides into the number, then sets it as NOT a prime, and breaks out
of the check. If the number IS a prime, then it outputs it.

Soz I am not the best to explain these things!

Any further information, just email me.

Love,

Steve
XX

for (i=2; i<=100; i++)
{
        if (i%100==0)
        {
            document.write("<BR>")
        };

        prime=true;

        for (j=2; j<i; j++)
        {
            if (i%j==0)
            {
                prime=false;
                break
            }
        };

    if (prime){document.write(i+" ")};
}


----- Original Message -----
From: dougwris
To: Javascript at LaTech.edu
Sent: Monday, January 06, 2003 3:29 AM
Subject: [Javascript] Generating Prime Numbers


I've written many modest scripts, but this one baffles me.  It generates all
the prime numbers under 2000.  Can anyone explain it to me?
Thx, Doug.


<script>
<!--
for (i=2; i<=100; i++) {
        if (i%100==0){document.write("<BR>")};
 prime=true;
 for (j=2; j<i; j++) {
            if (i%j==0){prime=false;break}
        };
 if (prime){document.write(i+" ")};
}
//-->
</script>




More information about the Javascript mailing list