JavaScript Prime Numbers
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Prime Numbers</title>
<style>
.maindiv {
width: 50%;
background-color: #CCFFFF;
text-align: center;
padding: 30px;
}
@media only screen and (max-width: 600px) {
.maindiv {
width: 100%;
padding: 20px;
}
}
</style>
</head>
<body>
<div class=”maindiv”>
<h1><u>Prime Numbers</u></h1>
<h3>
Find JavaScript prime numbers. If the number entered is not a prime, then find the closest prime
number.
</h3>
<p id=”prime”></p>
</div>
<script>
num = parseInt(prompt(“Enter any number”))
if (num == 1 || num == 0) {
document.getElementById(“prime”).innerHTML = num + ” is not a prime nor a composite number”
} else {
function isPrime(num) {
myPrime = 1
for (i = 2; i < num; i++) {
if (num % i == 0) {
myPrime = 0
break
}
}
if (myPrime == 1) {
document.getElementById(“prime”).innerHTML = num + ” is the prime number”
}
else if (myPrime == 0) {
isPrime(num + 1)
}
}
isPrime(num)
}
</script>
</body>
</html>