Check if the number is prime in JavaScript [duplicate]

2

Well, I made this code to show if the textbox number is prime, if a message appears in the paragraph with message id. But it does not work if someone could tell me where I'm going wrong. I would be grateful.

<html>
 <head>
  <meta charset='utf-8'/>
  <title></title>
  <script type="text/javascript" >
   function primo(num) {
    for (var i = 2; i < num; i++)
    if (num % i === 0) return false;
    return num !== 1;
    var resl = "O número" + primo(num) + "é primo";
	document.getElementById("mensagem").innerHTML = resl;
}
  </script>
 </head>
 <body>
 <p>
 <input type="text" id='name'/>
 </p>
<input type="button" name="botão" id="verificarvalor" value="Verificar" onclick = "primo(num)"/>
<p id="mensagem"></p>
 </div>
 </body>
</html>
    
asked by anonymous 13.04.2017 / 23:49

3 answers

8

I made it very quick here, removing the code that was after the return, which was ignored. I put it in the other function in which you call your main function. It's pretty basic, you can improve ...

EDIT

I have added some checks, if it is number and if it is different if 1 ...

<html>

<head>
  <meta charset='utf-8' />
  <title></title>
  <script type="text/javascript">
    function primo(num) {
    // verifica se o numero digitado é "1", que não é primo
     if(num!=1){
      for (var i = 2; i < num; i++)
        if (num % i == 0) return false;
      return num !== 1;
    }
    }

    function verificaPrimo() {
      var num = document.getElementById("name").value;
      var resl="";
      // verifica se é número
     if(!isNaN(num)){
      // verifica se é primo
      if (primo(num)) {
       resl = "O número " + (num) + " é primo";
        
      } else {
       resl = "O número " + (num) + " nao éprimo";
      }
      document.getElementById("mensagem").innerHTML = resl;
    }

else{
 document.getElementById("mensagem").innerHTML = "Vish, nem número é";
}
}
  </script>
</head>

<body>
  <p>
    <input type="text" id='name' />
  </p>
  <input type="button" name="botão" id="verificarvalor" value="Verificar" onclick="verificaPrimo()" />
  <p id="mensagem"></p>
  </div>
</body>

</html>
    
14.04.2017 / 00:17
6

Do this:

<html>
 <head>
  <meta charset='utf-8'/>
  <title></title>
 </head>
 <body>
 <p>
 <input type="text" id='name'/>
 </p>
<input type="button" name="botão" id="verificarvalor" value="Verificar">
<p id="mensagem"></p>
 </div>
 <script type="text/javascript" >
   function isPrime(num) {
      for(var i = 2; i < num; i++)
        if(num % i === 0) return false;
      return num !== 1;
    }
    // campos texto e botao
    var el = document.getElementById('name'), btn = document.getElementById('verificarvalor');
    // esperar click sobre o botao
    btn.addEventListener('click', function(e){
        e.preventDefault();
        // verificar se o valor digitado é um numero
        if(!isNaN(el.value)){
            if(isPrime(el.value)){
                alert(el.value + ' é primo');
            } else {
                alert(el.value + ' nao é primo');
            }
        } else {
            return false;
        }
    });
  </script>
 </body>
</html>

   function isPrime(num) {
	  for(var i = 2; i < num; i++)
		if(num % i === 0) return false;
	  return num !== 1;
	}
	// campos texto e botao
	var el = document.getElementById('name'), btn = document.getElementById('verificarvalor');
	// esperar click sobre o botao
	btn.addEventListener('click', function(e){
		e.preventDefault();
		// verificar se o valor digitado é um numero
		if(el.value && !isNaN(el.value)){
			if(isPrime(el.value)){
				alert(el.value + ' é primo');
			} else {
				alert(el.value + ' nao é primo');
			}
		} else {
			return false;
		}
	});
<html>
 <head>
  <meta charset='utf-8'/>
  <title></title>
 </head>
 <body>
 <p>
 <input type="text" id='name'/>
 </p>
<input type="button" name="botão" id="verificarvalor" value="Verificar">
<p id="mensagem"></p>
 </div>
 </body>
</html>

In any programming language (at least I know of) no code after return is executed. Also, in your code the assignments were poorly made, declaring primo(num) to the button would be invalid, because there is no longer any num in the given context, and the button has no value. Another thing is the placement of the script tag, it is always preferable to place it just after the set that will execute it, usually next to the tag </body> .

Alternatively, if you want something much simpler, you can do this:

<input type="text" id='name'/>
</p>
<input type="button" name="botão" id="verificarvalor" value="Verificar" onclick="primo()">
<p id="mensagem"></p>
</div>

And the javascript code:

function primo(){
    var el = document.getElementById('name'), msg = document.getElementById('mensagem');
    if(el.value && !isNaN(el.value)){
        if((el.value % 2) === 1){
            msg.innerHTML = "Numero: " + el.value + " e primo";
        } else {
            msg.innerHTML = "Numero: " + el.value + " nao e primo";
        }
    }   
}

If you prefer something even simpler, the solution is to replace this expression inside the if:

(el.value % 2) === 1

For this one:

el.value & 1
  

SOpt - Function to check if number is prime in Javascript

    
14.04.2017 / 00:15
4

SOURCE StudyMaths.co.uk

  

Filter to accept only numbers, and number of digits entered in the input equal to 12

     

maxlength="12" to prevent browser crashes .

function primo() {
  var number = document.getElementById("number").value;
    if (!isNaN(number)) {
       if (isPrime(number)) {
          document.getElementById("mensagem").innerHTML = number + " É primo!";
       }
       else {
         document.getElementById("mensagem").innerHTML = number + " Não é primo.";
       }
    }
    else {
        document.getElementById("mensagem").innerHTML = "Só aceita números, volta pra escola";
    }
}

function isPrime(n) {

   if (n < 2) {return false}
        if (n != Math.round(n)) {return false}
           var isPrime = true;

           for (var i = 2; i <= Math.sqrt(n); i++) {
               if (n % i == 0) {return false;}
            }

    return isPrime;
 }
<input id="number" value="0" maxlength="12" size="8" onclick="this.select()" />
<input type="button" value="Verificar" onclick="primo()" />
<p id="mensagem"> </p>

Examples of prime numbers: 104729 - 20173 - 1117111 - 777767777 - 16148168401

List of first 10000 prime numbers

  

To avoid freezing your browser, I limited the input to 12 digits

.

    
14.04.2017 / 00:37