How to detect parity of a number without operator%?

11

I have a variable that the server gives me with a value, I need to know if the number is par or odd , but without using %2 :

$.ajax({ 
    url:'/numero',
    type:'POST',
    success:function(num){
       // ¿Qué hago con num para saber qué es?
       // num.numero me da el valor del numero ej;5,7,2...
    }

})
    
asked by Travv 14.12.2017 в 14:24
source

4 answers

28

It's very simple: use the bit AND operator .

In binary, pairs have the last bit at 0 , while odd have the last bit at 1 : p>

  

1512 & 1 == > 0 (is par)
  1511 & 1 == > 1 (it's odd)

Therefore:

function espar( x ) {
  return !( x & 1 );
}
console.log(espar(1512));
console.log(espar(1511));
  

espar (1512) == > true
  espar (1511) == > false

I can not resist the moral : there are only 10 classes of people: those who know binary and those who do not; -)

    
answered by 14.12.2017 / 14:49
source
5

Divide the number by 2. The odd numbers will always return a decimal number while the pairs will not. Then you only have to check if it is a decimal converting the result to string and search for the point:

var value = prompt("Ingrese numero:");

var esPar = (parseInt(value)/2).toString().indexOf('.')==-1;

if(esPar){
  console.log("el numero es par");
}
else{
  console.log("el numero es impar");
}
    
answered by 14.12.2017 в 14:29
4

Why do not you just do a mathematical division operation? If dividing a number by 2 the result of the division is exact means that the number is even then we validate this with a regular expression, simply asking "if the result of the division contains a point means that it was not exact and that consequently the number is odd "

$("#preguntar").click(function(){
  var numero = $("#numero").val();
  
  var division = (Number(numero) / 2);
  var expresion = new RegExp(/\./);
  
  if(expresion.test(division.toString())){
    console.log('El número ingresado es impar');
  }else{
    console.log('El número ingresado es par');
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="numero">

<button id="preguntar">Par o impar</button>
    
answered by 14.12.2017 в 14:43
0

Knowing the last digit of your number you can decipher if the whole number is even or odd since it is known that the numbers ending in 0,2,4,6 and 8 are even, therefore

You can do the following:

$.ajax({ 
    url:'/numero',
    type:'POST',
    success:function(num){
       //Declaro todos los numeros en los que debe terminar los #s pares
       var pars = [0,2,4,6,8];
       //Verifico si el numero actual termina en uno de esos y asi veo cuando es par y cuando no
       if(pars.indexOf(parseInt(num.toString().charAt(num.toString().length-1))) >= 0)
          console.log("es par");
        else 
          console.log("es impar");
    }

});
    
answered by 14.12.2017 в 14:39