Check If a Number is Even Without Using the Modulo Operator in JavaScript



For a given integer number, write a program in JavaScript to check whether a number is odd or even and return the same to the user. It's pretty easy to check whether a number is even by using the modulo operator. But, in this article, we will be checking whether a number is even or not without using the modulo operator.

Using the for loop

In this approach, we are going to use the for loop to check whether a number is even or not. The idea is to take a Boolean flag variable as true and check it up to n times. If the flag gets its value back it means the value was even else not.

Example

In the below example, we are going to check whether a number is even or not by using the for loop approach.

// Returns true if n is even,
function isEven(n) {
   let isEven = true;
   for (let i = 1; i <= n; i++)
      isEven = !isEven;
   if (isEven)
      console.log(n + " is an Even number");
   else
      console.log(n + " is Odd");
}
// function call
isEven(101);
isEven(158);

Following is the output of the above code ?

101 is Odd
158 is an Even number

Using multiplication and division

Here, we are going to divide a number by 2 and then multiply the result by 2. If the result is the same as that of the original number, it is an even number.

Example

In this JavaScript program, we are going to check whether a number is even or not by using multiplication and division.

// Returns true if n is even,
function isEven(n) {
   // Return true if n/2 does not result
   // in a float value.
   if (parseInt(n / 2, 10) * 2 == n) {
      console.log(n + " is an Even number");
   } else {
      console.log(n + " is Odd");
   }
}
// function call
isEven(101);
isEven(158);

The above program will produce the following result ?

101 is Odd
158 is an Even number

Using the bitwise operator

In this approach, we are going to use the bitwise AND operator to check whether the specified number is even. If the result of AND operation between given number and 1 is 0, then, the number is even otherwise odd.

Example

The following JavaScript program shows how to check if a number is even without using modulo operator.

// Returns true if n is even,
function isEven(n) {
   // n&1 is 1, then odd, else even
   if (!(n & 1)) {
      console.log(n + " is an Even number");
   } else {
      console.log(n + " is Odd");
   }
}
// function call 
isEven(101);
isEven(158);

On running this code, you will get the below result ?

101 is Odd
158 is an Even number
Updated on: 2024-09-30T16:04:55+05:30

923 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements