Check if the number is Javascript prime

Asked

Viewed 10,473 times

2

Well, I made this code to show if the textbox number is prime, if a message will appear in the paragraph with message id. But it doesn’t work, if someone could tell me where I’m going wrong. I’d 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>

  • Visually you can experiment onclick=primo(this.value) and has code after the return.

  • 2

    actually a lot is wrong there.

  • a lot of things, why use onclick=primo(this.value) Voce would be taking the value of the boot... and then and a return the code is ignored...

3 answers

7


I did it very quickly here, removing the code that was then Return, which was ignored. I put it in the other function in which it calls its main function. It’s pretty basic, you can get better...

EDIT

I added some checks, if it’s number and if it’s 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>

  • if you type a letter returns prime

  • @Leocaracciolo, yes. Even if you type "1" ... I did just the example not to run too far from his code

  • Quiet, but could improve!!! Community would be happy.

  • @Leocaracciolo Editei :)

  • blz, giving upvote

  • the Vish was fun, rs :)

  • It’s freezing for big cousins ex: 16148168401

  • @Leocaracciolo here gave... And is not cousin. Freezing as?

  • in my cousin 16148168401 Uai, here it is freezing yes, take a look at https://answall.com/questions/198233/porque-um-script-congela-o-navegador-e-o-outro-n%C3%A3o-se-o-n%C3%Bamero-de-loops-%C3%A9-o-mesm

  • we need a third opinion http://www.onlineconversion.com/prime.htm

Show 5 more comments

6

Do so:

<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 the ones I know) no code after the return is executed. Also, in its code the assignments were poorly made, declare primo(num) for the button, it would be invalid, because for now it does not exist in a in the given context, and the button has no value. Another thing is tag placement script, it is always preferable to put right after the set that will run it, usually together with the tag </body>.

Alternatively, if you want something much simpler, you can do it like 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 code javascript:

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

This way:

el.value & 1

Sopt - Function to check if numero is prime in Javascript

  • So I’m still a student. I’m learning rss. This was an exercise passed by my teacher. And your code just didn’t help me so much because you put addeventlistener and the teacher just wants us to use what he taught. But thank you so much for the help and the tips.

  • @Uondaime if you have time edit for something much simpler to understand.

  • Ah, I’ll be very grateful. Hug!

  • @Uondaime there you have, something relatively simpler.

  • "empty field" is returning prime. This is the expected behavior even in javascript?

  • @diegofm sorry ?

  • I opened the snippet and clicked on "calculate" with the field with nothing, and returned "is prime". That’s the expected behavior even?

  • @diegofm probably because of the conditions that are there, I removed the "empty field", but continues to validate 0, despite being neutral.

Show 3 more comments

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 crashing.

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>

Prime number examples: 104729 - 20173 - 1117111 - 777767777 - 16148168401

List of first 10000 prime numbers

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

Because one script freezes the browser and the other one doesn’t if the number of loops is the same.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.