Write the javascript program display whether a number is prime or not.
The Prime number is a whole number that will divide by 1 or itself is called a prime number.
In this program, you will check whether a given number is prime or not in the JavaScript program using for loop
<!DOCTYPE html>
<html>
<body>
<script>
function PrimeNo()
{
var i,flag=0;
var n=prompt("enter a number");
for(i=1;i<=n;i++)
{
if(n%i==0)
{
flag+=1;
}
}
if(flag==2)
{ document.write(n+" is prime number"); }
else{ document.write(n+" is not a prime number"); }
}
</script>
<form>
<input type="button" value="prime number" onclick="PrimeNo();">
</form>
</body>
</html>
PrimeNo()
function will get called.PrimeNo()
function, you will take input from the user using the prompt method, and you will store the input value in variable n
. for(i=1; i<=n;i++)
, and when input value n is divisible by exactly two times during an iteration of the for-loop that means n is a prime number.Flag
variable is used for counting how many times an input value n
is divisible.flag
value is 2 then the number is prime otherwise the number is not prime.This program is the same as the above program only difference is here you have taken input through the HTML input box.
<html>
<body>
<form name="f1">
enter the number <input type="number" name="no">
<input type="button" value="output" onclick="PrimeNo()" value="output">
</form>
<p id="prime">output here</p>
<script>
function PrimeNo()
{
var i,flag=0;
var p=" ";
var a=parseInt(document.f1.no.value);
for(i=1;i<=a;i++)
{
if(a%i==0)
{
flag+=1;
}
if(flag==2)
{p=a+" is prime number"; }
else{ p=a+" is not a prime number";}
}
var d=document.getElementById("prime").innerHTML=p;
}
</script>
</body>
</html>
Click on the 'run now' button to view the output
var d=document.getElementById("prime").innerHTML=p;
.<p id="prime">output here</p>
when you run the program, in place of 'output here ' variable p value will display.