Knowing if the number is odd or even

Asked

Viewed 53,067 times

29

I wonder why nothing happens to my code. Even the variable n the alert appears, but then nothing else happens.

var n = prompt("Digite um numero");
var total=n/2;
if(n/2=0){
    alert("Par");
}
if(n/2=1){
    alert("Impar");
}
alert(total);

7 answers

50


In ifComparisons do not use a sign =, but yes two signs or three, as in the example:

  • if (n/2 == 0) { equals comparison
  • if (n/2 === 0) { identical comparison

Your code must be something like:

Note: your code does not check if the value is odd or even really, for this use one of these methods described in Checking whether it is odd or even and this example is just to understand how to use the ifs:

var n = prompt("Digite um numero");
var total=n/2;
if(n/2 == 0){
    alert("Par");
}
if(n/2 == 1){
    alert("Impar");
}
alert(total);

The use of if in this way if (1=1) in Javascript will issue the following error:

Uncaught Referenceerror: Invalid left-hand side in assignment

Checking whether it is odd or even

  • Arithmetic: if (variavel % 2 === 0) if equal to 0 is even, if it’s not odd

  • Arithmetic: if (variavel % 2 !== 0) other than 0 is odd if not even

  • Bitcheck: if (variavel & 1) if it’s 0 is even, if it’s not odd

  • With bitcheck and "~": if (~ variavel & 1) if it’s 0 is odd if not even

A test to compare performance: http://jsperf.com/bitcheck-vs-arithmetic-odd-and-even

Example:

var n = prompt("Digite um numero");
var total = n/2;

if(n & 1){
    alert("Impar");
} else {
    alert("Par");
}

alert(total);

Comparison operators

Equality Operators

  • Equal/Equivalent (==) is used to compare if values are equal, for example:

console.log(1 == 1);     // true
console.log("1" == 1);   // true
console.log(1 == '1');   // true
console.log(0 == false); // true

  • Different/not equivalent (!=) is used to make comparisons are not equal:

console.log(1 != 2);     // true
console.log(1 != "1");   // false
console.log(1 != '1');   // false
console.log(1 != true);  // false
console.log(0 != false); // false

  • Identical / strictly equivalent (===) is used to compare if both values are of the same value type, differentiating integers from with floating point, integer boolean, string integer, etc:

console.log(3 === 3);     // true
console.log(3 === '3');   // false
console.log(0 === false); //false

  • Not identical/strictly nay equivalent (!==) is used to compare if both values are of different value types:

console.log(3 !== 3);     // false
console.log(3 !== '3');   // true
console.log(0 !== false); // true
console.log(0 !== 0);     // false

17

  1. to make comparisons is used ==. Example: if(x == y)

  2. to know if the number is even or odd it is better to use the rest operator(%).

The code at the end could look like this:

var n = prompt("Digite um numero");
var total=n/2;
if(n%2 == 0){
	alert("Par");
}else{
	alert("Impar");
}
alert(total);

If n rest 2 equals 0 is even, otherwise it is odd.

  • Remember that the operator == compares whether the value of two objects is equal and the operator === compares whether the value and object types are equal. For example 'true' == true results in true; 'true' === true returns false.

12

To know if a given number is even or odd the best way is by using the modulus operator/rest, %. Which returns the rest of the division of two numbers.

If n % 2 der rest zero, the number is even, and odd otherwise.

var n = prompt("Digite um numero");
var total = n / 2;
var resultado = total % 2 == 0 ? 'Par' : 'Impar';
alert(total + ' é ' + resultado);

5

Another interesting (and economical) way to do this check is through bit-to-bit operation &

Examples

  • Unique

    alert(3 & 1 ? "Ímpar" : "Par"); //imprime "Ímpar", pois retorna o ultimo bit da operação bit-a-bit & (Nesse caso, 1)

        11
        01 &
        01
    
  • Par

    alert(4 & 1 ? "Ímpar" : "Par"); //imprime "Par", pois retorna o ultimo bit da operação bit-a-bit & (Nesse caso, 0)

         100
         001 &
         000
    

4

var n = prompt("Digite um numero");
var total = n/2;
if(n / 2 = 0) {
    alert("Par");
}
if(n / 2 = 1){
    alert("Impar");
}
alert(total);

Friend when you use: var 'total = n/2' you’re just dividing this value, there’s no way to know if it’s even or odd this way.

You need to use the operator % that will give the result of the surplus of the division, and by means of this surplus it is known whether it is even or odd. Very simple neh ?

just change:

var total = n / 2;

for:

var tola = n % 2;

something else is not:

if(n/2 = 1){
}

but yes :

if(total == 0){
    alert("par");
}

in short, the code can look like this:

var n = prompt("digite numero");
var resto = n % 2;

if (resto == 0) {
    console.log(n + " par");
} else {
    console.log(n + " impar");
}

-2

<!DOCTYPE html>
<html lang="pt-br">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>exercicio02</title>
</head>

<body>
    <script>
       
        //Complementando o raciocínio citado a cima. Usa um Template strings ${}
        

        var n = prompt('Digite um número ');
        var resultado = n % 2 ===0? 'par':'impar'; //função ternária é bem básica
            alert(`número ${n} é ${resultado}`); // a propriedade do alert está entre crase.

    </script>
</body>

</html>

//Complementing the above reasoning. Uses a Template strings ${} //ternary function is very basic:

var n = prompt('Type a number'); var result = n % 2 ===0? 'even':'odd'; Alert(número ${n} é ${resultado}); // Alert property is among crase.

-2

I think there are some mistakes, see:

var n = prmpt('digite o numero');
var total=n/2;
if(n/2==0){
alert('par");
}

Obs: notice that the equality operator is two == and not one = . in the other if statement you also need to adjust ok.

var n = prompt("digite um numero");
var total=n/2;
if(n/2=0){
    alert("par");
}
if(n/2=1){
    alert("impar");
}
alert(total);

Browser other questions tagged

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