Forum Moderators: open
4 divided by 3 = 1 with a remainder of 1, so 4 is not divisible by 3. 4 divided by 2 = 2 with a remainder of 0, so 4 is divisible by 2.
JavaScript provides the modulo operator (%) to get the remainder. 4 modulo 3 (4 % 3) = 1. 4 modulo 2 (4 % 2) = 0.
So, in a very simple form, your loop will need to check the remainder of all the digits between your number and 1. If any of them give you a remainder of 0, then the number is not prime.
This should be enough to get you going, but if you find that you still can't create the script to produce the results you want, then let me know and I'll post a solution.
well i've got this so far....
This script will assume primeness, until it finds a factor of n. So if the number is NOT prime, it'll usually find out pretty quickly. The script may run slowly on really large primes, but that's just the nature of the beast.
cut and paste this onto a page and you'll see how it works.
<script>
for(c=0;c<=100;c++){
document.write('<br/>'+c+' is '+(isprime(c)?'prime':'not prime'));
}
function isprime(num){
// now let's see if it's prime.
// set a little boolean flag saying if num is prime. we'll set it to true,
// then we'll set it to false only if we manage to find a factor other than 1 or num
var prime = true;
// first check for 1 or 2 or 3. that's easy.
if (num == 1 ¦¦ num == 2 ¦¦ num == 3) {
prime=true; // this line is redundant
}else{
// it's not a 1 or a 2 or a 3. So now we need to do some looping...
// loop i from 2 to num/2 (rounded up), check if num is divisible by i
// we only need to loop to num/2, since no factors will be larger than that
for (var i=2;i<=Math.ceil(num/2);i++) {
if (num % i == 0) {
prime=false;
break; // stop when we find a factor
}
}
}
return prime;
}
</script>