# Displaying Prime numbers in range

Enter the First Number

Enter the Last Number

Click

Is there any code. ?

1 Like
``````&lt;!DOCTYPE html&gt;

&lt;html&gt;

&lt;body&gt;

&lt;h1&gt;Displaying Prime numbers in range&lt;/h1&gt;

Enter the First Number &lt;input id="N"&gt;&lt;br&gt;&lt;br&gt;

Enter the Last Number  &lt;input id="LN"&gt;&lt;br&gt;&lt;br&gt;

&lt;hr color="cyan"&gt;

&lt;center&gt;&lt;button onclick="Prime()"&gt;Click&lt;/button&gt;

&lt;p id="demo"&gt;&lt;/p&gt;

&lt;script&gt;

function Prime()

{

var i,v,flag=0,number,number1,mess;

number = Number(document.getElementById("N").value);

number1 = Number(document.getElementById("LN").value);

//mess = document.getElementById("demo");

for (v=number;v&lt;=number1;v++){

for(i=2; i &lt;= v/2; i++)

{

if(v%i == 0)

{

flag = 1;

break;

}

}

if(flag == 0)

{

alert (v +" - The number is Prime");

}

else

{

alert (v +" - The number is not Prime");

}

}

}

&lt;/script&gt;

&lt;/body&gt;

&lt;/html&gt;
``````

Iâ€™ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The â€śpreformatted textâ€ť tool in the editor (`</>`) will also add backticks around text.

Note: Backticks are not single quotes.

1 Like

Try cleaning your code a bit to get quicker responses in the future, but anyway, here is the crux of your code

``````let smallNumber = 4
let bigNumber = 20
let flag=0;
for (let v=smallNumber;v<=bigNumber;v++){
for(let i=2; i<= v; i++){
if(v%i == 0){
flag = 1;
break;
}
}
if(flag == 0){
console.log(v +" - The number is Prime");
} else{
console.log(v +" - The number is not Prime");
}
}
``````

This doesnâ€™t work because there are 2 fundamental problems

1. In your inner loop you are including the number being tested and a number is of course divisible by itself and your flag will be turned on, so you need to stop the inner loop before it reaches the number being tested.
2. When you do find a non-prime number and turn the flag on inside your inner loop, it never gets reset back to zero for the next number being tested, you need to reset your flag back to zero before testing a new number.
1 Like