Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the code show prime and non-prime both answers?

I am getting if and else both results from my JS Code even after using flags and break. What seems to be the possible reason?

function myFunction(){
  let x = document.getElementById("int").value;
  const rootx = Math.sqrt(x);
  let textx = "";
  let isPrimeX = true;
  //checking the prime of x input
 for (let i = 2; i<=rootx; i++){
    if(x % i === 0 || x<=1 || x>2){
      textx += x + " is not a prime number"
      let isPrimeX = false;
      break;
    }
 }if(isPrimeX == true){
  textx += x + " is a Prime Number";
 }
 document.getElementById('demo').innerHTML = textx;
  }

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you are redeclaring isPrimeX

just remove let like this

function myFunction(){
  let x = document.getElementById("int").value;
  const rootx = Math.sqrt(x);
  let textx = "";
  let isPrimeX = true;
  //checking the prime of x input
 for (let i = 2; i<=rootx; i++){
    if(x % i === 0 || x<=1 || x>2){
      textx += x + " is not a prime number"
      isPrimeX = false;
      break;
    }
 }if(isPrimeX == true){
  textx += x + " is a Prime Number";
 }
 document.getElementById('demo').innerHTML = textx;
  }


Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading