![]() |
VOOZH | about |
Given a positive integer n as a dividend and another number m (a form of 2^k), find the quotient and remainder without performing actual division
Examples:
Input : n = 43, m = 8
Output : Quotient = 5, Remainder = 3Input : n = 58, m = 16
Output : Quotient = 3, Remainder = 10
In this, we are using a bitwise representation of a number for understanding the role of division of any number by divisor of form 2^k. All numbers which are power of two include only 1 set bits in their representation and we will use this property.
For finding the remainder we will take logical AND of the dividend (n) and divisor minus 1 (m-1), this will give only the set bits of dividend right to the set bit of divisor which is our actual remainder in that case.
Further, the left part of the dividend (from the position of set bit in divisor) would be considered for quotient. So, from dividend (n) removing all bits right from the position of set bit of divisor will result in the quotient, and right shifting the dividend log2(m) times will do this job for finding the quotient.
Note: Log2(m) will give the number of bits present in the binary representation of m.
Below is the implementation:
Remainder = 3 Quotient = 5
Time Complexity: O(1)
Auxiliary Space: O(1)