Given a number N, the task is to find the remainder when N is divided by 4 using Bitwise AND operator.
Input: N = 98 Output: 2 Explanation: 98 % 4 = 2. Hence the output is 2. Input: 200 Output: 0 Explanation: 200 % 4 = 0. Hence output is 0.
For solving the above-mentioned problem we can use a naive method by using the Modulo (%) operator to find the remainder. But, the Modulo operator is computationally expensive and the method is inefficient.
If we carefully observe the binary representation of N and its remainder with 4, we observe that remainder is simply the rightmost two bits in N. To get the rightmost two bits in number N, we perform bitwise AND (&) with 3 because 3 in binary is 0011. To understand the approach better let us have a look at the image below:
Below is the implementation of the above approach:
Time Complexity: O(1)
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Program to find remainder when large number is divided by 11
- Program to find remainder when large number is divided by r
- Program to find remainder without using modulo or % operator
- Find the remainder when First digit of a number is divided by its Last digit
- Check if the remainder of N-1 factorial when divided by N is N-1 or not
- Largest number by which given 3 numbers should be divided such that they leaves same remainder
- Largest number less than or equal to Z that leaves a remainder X when divided by Y
- Minimum number of operations on a binary string such that it gives 10^A as remainder when divided by 10^B
- Count of integers obtained by replacing ? in the given string that give remainder 5 when divided by 13
- Multiply any Number with 4 using Bitwise Operator
- Find subsequences with maximum Bitwise AND and Bitwise OR
- Find permutation with maximum remainder Sum
- Program to find Quotient And Remainder in Java
- Find numbers that divide X and Y to produce the same remainder
- Find all the possible remainders when N is divided by all positive integers from 1 to N+1
- Find Quotient and Remainder of two integer without using division operators
- Find the sums for which an array can be divided into sub-arrays of equal sum
- Find all the possible numbers in a range that can be evenly divided by its digits
- Total pairs in an array such that the bitwise AND, bitwise OR and bitwise XOR of LSB is 1
- Find bitwise AND (&) of all possible sub-arrays
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.