The following table provides few examples of prime numbers.
Number
Divisor
Result
13
1, 13
Prime Number
15
1, 3, 5, 15
Not a Prime Number
47
1, 47
Prime Number
Using for loop
In the following example, we will check whether the given number (7) is a Prime number or not using for loop.
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<h1>JS Prime Number</h1>
<script>
varnum=7;
vari=1;
varcount=0;
for(i=1; i<=num; i++)
{if(num%i==0)
count++;
}
if(count==2)
document.write(num+" is a prime number");
elsedocument.write(num+" is not a prime number");
</script>
</body>
</html>
In the following example, we will check whether the given number (7) is a Prime number or not using while loop.
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<h1>JS Prime Number</h1>
<script>
varnum=7;
vari=1;
varcount=0;
while(num>=i)
{if(num%i==0)
count++;
i++;
}
if(count==2)
document.write(num+" is a prime number");
elsedocument.write(num+" is not a prime number");
</script>
</body>
</html>
In the following example, we will check whether the given number (7) is a Prime number or not using do while loop.
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<h1>JS Prime Number</h1>
<script>
varnum=7;
vari=1;
varcount=0;
do {
if(num%i==0)
count++;
i++;
}while(i<=num);
if(count==2)
document.write(num+" is a prime number");
elsedocument.write(num+" is not a prime number");
</script>
</body>
</html>
In the following example, we will check whether the given number (12) is a Prime number or Composite number.
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<h1>JS Prime Number or Composite Number</h1>
<script>
varnum=12;
vari;
varcount=0;
for(i=1; i<=num; i++)
{if(num%i==0)
count++;
}
if(count==2)
document.write(num+" is a prime number");
elsedocument.write(num+" is a composite number");
</script>
</body>
</html>