Find square root of a number using Bit Manipulation
Given a non-negative integer N, the task is to find the square root of N using bitwise operations. If the integer is not the perfect square, return largest integer that is smaller than or equal to square root of N i.e., floor(√N).
Input: N = 36
Explanation: The square root of 36 is 6.
Input: N = 19
Explanation: The square root of 19 lies in between
4 and 5 so floor of the square root is 4.
Approach: To solve the problem using bitwise operators follow the below idea:
Let’s assume that square root of N is X i.e., N ≥ X2.
Let’s consider binary representation of X = ( bm, bm-1, ….., b2, b1, b0 ) where bi represents the ith bit in binary representation of X. Since, the value of each bits can either be 1 or 0, we can represent
X = ( am + am-1 + . . . + a2 + a1 + a0 ) where ai = 2i or ai = 0.
Consider an approximate solution:
Sj = ( am + am-1 + . . . + aj ) and also let Sj = Sj+1 + 2j.
If Sj2 ≤ X2 ≤ N then jth bit is set and 2j is part of the answer. Otherwise, it is 0.
Follow the below illustration for a better understanding.
N = 36 , result = 0
Binary representation of N: 100100
MSB of N is 5.
Initially result = 0, a = 25 = 32
For 5th bit:
=>(result + a) = (0 + 32) = 32, and 32 * 32 = 1024 is greater than N (36)
=> update a = a/2 = 32/2 = 16, result = 0
For 4th bit:
=> Now, (result + a) = 16, and 16 * 16 = 256 is greater than N (36)
=> update a = a/2 = 16/2 = 8
For 3rd bit:
=> Now, (result + a) = 8, and 8 * 8 = 64 is greater than N (36)
=> update a = a/2 = 8/2 = 4
For 2nd bit:
=> Now, (result + a) = 4, and 4 * 4 = 16 is less than N (36) so add (a) to result
=> update a = a/2 = 4/2 = 2, result = 4
For 1st bit:
=> Now, (result + a) = (4+2) =6, and 6 * 6 = 36 is equal to N (36) so add (a) to result
=> update a = a/2 = 2/2 = 1, result = 6
So, the final result = 6.
Based on the above observation in each bit position find the contribution of that bit in the answer and add that value to the final answer. Follow the steps mentioned below to implement the above approach:
- Initialize a variable (say result) to store the final answer.
- Start iterating from the MSB of N:
- If the square of (result + ai) is at most N then that bit has contribution in the result [where ai is 2i].
- So add the value ai in result.
- After iteration is over, the value stored at result is the required answer.
Below is the implementation of the above approach:
Time Complexity: O(log N)
Auxiliary Space: O(1)
Please Login to comment...