Please correct me I want to display all prime numbers in range..I am getting theb specified number but not in range not sure i hv gone wrong

Displaying Prime numbers in range

Enter the First Number


Enter the Last Number

Click

Is there any code. ?

1 Like
<!DOCTYPE html>

<html>

<body>

<h1>Displaying Prime numbers in range</h1>

Enter the First Number <input id="N"><br><br>

Enter the Last Number  <input id="LN"><br><br>

<hr color="cyan">

<center><button onclick="Prime()">Click</button>

<p id="demo"></p>

<script>

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<=number1;v++){

  for(i=2; i <= 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");

  }

        }

      }  

</script>

</body>

</html>

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.

markdown_Forums

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

Sure,thanks will follow and appreciate for your help!!