Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for even numbers in Java without modulo operator

How would I do this in Java? Find if a number is divisible by 2, if the last digit is even. (0,2,4,6,8) Example: 128 is, 129 is not

like image 578
JavaNewGirl Avatar asked Dec 08 '12 21:12

JavaNewGirl


People also ask

How do you check if a number is an even number in Java?

Check whether the number is even or odd by using bitwise XOR. If the number after bitwise XOR with 1 is equal to the original number + 1, then it is an even number. If not equal, then it is an odd number.

How do you calculate modulus without operator?

This is the basic formula: dividend = divisor * quotient + remainder From this equation you can calculate the remainder.

How can you tell a number is even or odd without using any condition or loop?

We can divide the number by 2, then check whether the remainder is 0 or not. if 0, then it is even. Otherwise we can perform AND operation with the number and 1. If the answer is 0, then it is even, otherwise odd.

How do you check given number is even or not?

A number that is divisible by 2 and generates a remainder of 0 is called an even number. All the numbers ending with 0, 2, 4, 6, and 8 are even numbers. On the other hand, number that is not divisible by 2 and generates a remainder of 1 is called an odd number.


2 Answers

if((n|1)==n)
  System.out.println("odd");
else
  System.out.println("even");

Reason: number is odd if the LSB is 1, and even otherwise. When n|1 is done, LSB of odd stays the same so the resulting number is not changed, while LSB of a even number becomes 1, thus changing the number.

like image 57
prashant Avatar answered Oct 01 '22 11:10

prashant


see if the the right most bit is 1 then its not, by using bitwise operators

perform logical and with (for example)

yourNumber & 1
like image 26
jmj Avatar answered Oct 01 '22 11:10

jmj