The Wayback Machine - https://web.archive.org/web/20240910135043/https://www.geeksforgeeks.org/find-square-root-of-a-number-using-bit-manipulation/
Open In App

Find square root of a number using Bit Manipulation

Last Updated : 06 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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).

Examples:

Input: N = 36
Output: 6
Explanation:  The square root of 36 is 6.

Input: N = 19
Output: 4
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.

Illustrations:

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:

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find square root
int square_root(int N)
{
    // Find MSB (Most significant Bit) of N
    int msb = (int)(log2(N));
 
    // (a = 2^msb)
    int a = 1 << msb;
    int result = 0;
    while (a != 0) {
 
        // Check whether the current value
        // of 'a' can be added or not
        if ((result + a) * (result + a) <= N) {
            result += a;
        }
 
        // (a = a/2)
        a >>= 1;
    }
 
    // Return the result
    return result;
}
 
// Driver Code
int main()
{
    int N = 36;
 
    // Function call
    cout << square_root(N);
    return 0;
}


C




// C code to implement the approach
 
#include <math.h>
#include <stdio.h>
 
// Function to find square root
int square_root(int N)
{
    // Find MSB(Most significant Bit) of N
    int msb = (int)(log2(N));
 
    // (a = 2^msb)
    int a = 1 << msb;
    int result = 0;
    while (a != 0) {
 
        // Check whether the current value
        // of 'a' can be added or not
        if ((result + a) * (result + a) <= N) {
            result += a;
        }
 
        // (a = a/2)
        a >>= 1;
    }
 
    // Return the result
    return result;
}
 
// Driver Code
int main()
{
    int N = 36;
 
    // Function call
    printf("%d\n", square_root(N));
    return 0;
}


Java




// Java code to implement the approach
 
import java.io.*;
 
class GFG {
 
    // Function to find square root
    static int square_root(int N)
    {
        // Find MSB(Most significant Bit) of N
        int msb = (int)(Math.log(N) / Math.log(2));
 
        // (a = 2^msb)
        int a = 1 << msb;
        int result = 0;
        while (a != 0) {
 
            // Check whether the current value
            // of 'a' can be added or not
            if ((result + a) * (result + a) <= N) {
                result += a;
            }
 
            // (a = a/2)
            a >>= 1;
        }
 
        // Return the result
        return result;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 36;
 
        // Function call
        System.out.println(square_root(N));
    }
}


Python3




# Python code to implement the approach
 
import math
 
# Function to find square root
def square_root (N):
   
    # Find MSB(Most significant Bit) of N
    msb = int(math.log(N, 2))
     
    # (a = 2 ^ msb)
    a = 1 << msb
    result = 0
    while a != 0:
       
        # Check whether the current value
        # of 'a' can be added or not
        if (result + a) * (result + a) <= N :
            result += a
         
        # (a = a / 2)
        a >>= 1
         
    # Return the result
    return result
 
 
# Driver Code
if __name__ == '__main__':
    N = 36
     
    # Function call
    print(square_root(N))


C#




// C# code to implement the approach
 
using System;
 
public class GFG{
     
    // Function to find square root
    static int square_root(int N)
    {
        // Find MSB(Most significant Bit) of N
        int msb = (int)(Math.Log(N) / Math.Log(2));
 
        // (a = 2^msb)
        int a = 1 << msb;
        int result = 0;
        while (a != 0) {
 
            // Check whether the current value
            // of 'a' can be added or not
            if ((result + a) * (result + a) <= N) {
                result += a;
            }
 
            // (a = a/2)
            a >>= 1;
        }
 
        // Return the result
        return result;
    }
 
    // Driver Code
    public static void Main()
    {
        int N = 36;
 
        // Function call
        Console.WriteLine(square_root(N));
    }
}
 
// This code is contributed by Ankthon


Javascript




function square_root(N)
{
    // Find MSB(Most significant Bit) of N
    let msb = parseInt(Math.log2(N));
 
    // (a = 2^msb)
    let a = 1 << msb;
    let result = 0;
    while (a != 0) {
 
        // Check whether the current value
        // of 'a' can be added or not
        if ((result + a) * (result + a) <= N) {
            result += a;
        }
 
        // (a = a/2)
        a >>= 1;
    }
 
    // Return the result
    return result;
}
 
let N = 36;
 
    // Function call
    let ans = square_root(N);
    console.log(ans);
 
// This code is contributed by akashish.


Output

6

Time Complexity: O(log N)
Auxiliary Space: O(1)



Similar Reads

Digital Root (repeated digital sum) of square of an integer using Digital root of the given integer
Given an integer N, the task is to find the digital root N2 using the digital root of N. Digital Root of a positive integer is calculated by adding the digits of the integer. If the resultant value is a single digit, then that digit is the digital root. If the resultant value contains two or more digits, those digits are summed and the process is r
6 min read
Winner in the Rock-Paper-Scissor game using Bit manipulation
Two players are playing a series of games of Rock–paper–scissors. There are a total of N games played represented by an array arr[][] where arr[i][0] is the move of player one and arr[i][1] is the move of the player two in the ith game from the set {'R', 'P', 'S'}. The task is to find the winner of each of the game. Note that the game is a draw if
6 min read
Store two numbers in one Byte using Bit manipulation
Given two values A and B (A, B &lt; 16), the task is to store the numbers in one byte. Examples: Input: A = 5, B = 9Output: 89Explanation: 5 in binary form is 0101 and the binary form for 9 is 1001. Since 1 byte contains 8 bits, we can store these two nibbles in that 1 bit, forming 01011001 which when converted into decimal becomes 89. Input: A = 2
8 min read
Print all Palindromic Partitions of a String using Bit Manipulation
Given a string, find all possible palindromic partitions of a given string. Note that this problem is different from Palindrome Partitioning Problem, there the task was to find the partitioning with minimum cuts in input string. Here we need to print all possible partitions. Example: Input: nitinOutput: n i t i n n iti n nitin Input: geeksOutput: g
10 min read
Check if a number is perfect square without finding square root
Check whether a number is a perfect square or not without finding its square root. Examples: Input: n = 36 Output: Yes Input: n = 12 Output: No Recommended PracticeCheck perfect squareTry It! Method 1:The idea is to run a loop from i = 1 to floor(sqrt(n)) and then check if squaring it makes n. Below is the implementation: C/C++ Code // C++ program
9 min read
Maximize the Expression | Bit Manipulation
Given two positive integers A and B. Let's define D such that B AND D = D. The task is to maximize the expression A XOR D.Examples: Input: A = 11 B = 4 Output: 15 Take D = 4 as (B AND D) = (4 AND 4) = 4. Also, (A XOR D) = (11 XOR 4) = 15 which is the maximum according to the given condition. Input: A = 9 and B = 13 Output: 13 Naive approach: Since
7 min read
Maximize the expression (A AND X) * (B AND X) | Bit Manipulation
Given two positive integers A and B such that A != B, the task is to find a positive integer X which maximizes the expression (A AND X) * (B AND X).Example: Input: A = 9 B = 8 Output: 8 (9 AND 8) * (8 AND 8) = 8 * 8 = 64 (maximum possible)Input: A = 11 and B = 13 Output: 9 Naive approach: One can run a loop from 1 to max(A, B) and can easily find X
6 min read
All about Bit Manipulation
Bit Manipulation is a technique used in a variety of problems to get the solution in an optimized way. This technique is very effective from a Competitive Programming point of view. It is all about Bitwise Operators which directly works upon binary numbers or bits of numbers that help the implementation fast. Below are the Bitwise Operators that ar
14 min read
What is Bit Manipulation
Bit manipulation is the process of manipulating individual bits or groups of bits in a binary representation of data. It involves performing logical and arithmetic operations on binary digits or bits to achieve a desired result. How to Perform Bit Manipulation?Bit manipulation is performed using bit-wise operators, which operate on individual bits
4 min read
Bit Manipulation technique to replace boolean arrays of fixed size less than 64
Space complexity is the most underestimated asset by programmers. One can barely see a Memory Limit Exceed (MLE) while submitting a solution. But, saving memory is the most important thing a programmer should take care about. If one needs to create an Application for a user, it should be made as memory efficient as one can. Boolean arrays have been
10 min read
Bit Manipulation for Competitive Programming
Bit manipulation is a technique in competitive programming that involves the manipulation of individual bits in binary representations of numbers. It is a valuable technique in competitive programming because it allows you to solve problems efficiently, often reducing time complexity and memory usage. Table of Content Bitwise OperatorsUseful Bitwis
15+ min read
Find square root of number upto given precision using binary search
Given a positive number n and precision p, find the square root of number upto p decimal places using binary search. Note : Prerequisite : Binary search Examples: Input : number = 50, precision = 3 Output : 7.071 Input : number = 10, precision = 4 Output : 3.1622 We have discussed how to compute the integral value of square root in Square Root usin
9 min read
Find smallest perfect square number A such that N + A is also a perfect square number
Given a positive number N. The task is to find out the smallest perfect square number A such that N + A is also a perfect square number or return -1.Examples: Input: N = 3 Output: 1 Explanation: As 1 + 3 = 4 = 22 Input: N=1 Output: -1 Naive Approach: Traverse M from {1, 2, 3, 4, 5...} and check whether (N + M * M) is a perfect square number or not.
9 min read
Why do we check up to the square root of a number to determine if that number is Prime?
Why do we check up to the square root of a number to determine if that number is prime?Prime numbers are natural numbers greater than 1 which are divisible only by 1 and itself. Examples include 2, 3, 5, 7, 11, 13, etc. (1 is neither prime nor composite). Here is the code to check whether a number is prime or not. As, the loop checks for each numbe
3 min read
Find the index at which bit must be set to maximise distance between next set bit
Given a binary array arr[]. The task is to find the position of any 0 in arr[] such that the distance between two set bits is maximized. Examples Input: arr = [1, 0, 0, 0, 1, 0, 1]Output: 2Explanation: Flip the bit at arr[2] Input: arr = [1, 0, 0, 0]Output: 3 Approach: The problem can be solved by finding the longest distance between adjacent set b
5 min read
Find X in range [1, N] of bit size A[i] such that X^2's bit size is not present in Array
Given an array A of N integers, where: Each element of array represents the bit size of an imaginary unsigned integer datatype.If ith imaginary datatype has a size of A[i] bits, then it can store integers from size 0 to 2A[i]-1. The task is to check if there exist some integer X, such that: X is in range 1 to NX can fit in a datatype of bit size A[
8 min read
Find array elements with rightmost set bit at the position of the rightmost set bit in K
Given an array arr[] consisting of N and an integer K, the task is to print the elements of arr[] whose rightmost set bit is at the same position as the rightmost set bit in K. Examples: Input: arr[] = { 3, 4, 6, 7, 9, 12, 15 }, K = 7Output: { 3, 7, 9, 15 }Explanation:Binary representation of K (= 7) is 0111.Rightmost set bit in 7 is at position 1.
11 min read
Find if there is a pair in root to a leaf path with sum equals to root's data
Given a binary tree, find if there is a pair in root to a leaf path such that sum of values in pair is equal to root's data. For example, in below tree there are no pairs in any root to leaf path with sum equal to root's data. The idea is based on hashing and tree traversal. The idea is similar to method 2 of array pair sum problem. Create an empty
8 min read
Square root of a number without using sqrt() function
Given a number N, the task is to find the square root of N without using sqrt() function. Examples: Input: N = 25 Output: 5 Input: N = 3 Output: 1.73205 Input: N = 2.5 Output: 1.58114 Approach 1: We can consider (?x-?x)2 = 0.Replacing one of the ?x's with y, then the equation becomes (y-?x)2 =&gt; y2 - 2y?x + x = 0=&gt; ?x = (y2 + x) / 2y=&gt; ?x =
14 min read
Square root of a number using log
For a given number find the square root using log function. Number may be int, float or double. Examples: Input : n = 9Output : 3 Input : n = 2.93Output : 1.711724 We can find square root of a number using sqrt() method: C/C++ Code // C++ program to demonstrate finding // square root of a number using sqrt() #include&lt;bits/stdc++.h&gt; int main(v
3 min read
Long Division Method to find Square root with Examples
Given an integer X which is a perfect square, the task is to find the square root of it by using the long division method. Examples: Input: N = 484 Output: 22 222 = 484 Input: N = 144 Output: 12 122 = 144 Approach: Long division is a very common method to find the square root of a number. The following is the stepwise solution for this method: 1. D
10 min read
Find Square Root under Modulo p | (When p is product of two primes in the form 4*i + 3)
Given an integer N and an integer P denoting the product of two primes, the task is to find all possible Square Root of N under modulo P if it exists. It is given that P is the product of p1 and p2, where p1 and p2 are prime numbers of the form 4i + 3 where i is any integer. Some examples of such prime numbers are (7, 11, 19, 23, 31). Examples: Inp
15+ min read
Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)
Given a number 'n' and a prime 'p', find square root of n under modulo p if it exists. It may be given that p is in the form for 4*i + 3 (OR p % 4 = 3) where i is an integer. Examples of such primes are 7, 11, 19, 23, 31, ... etc,Examples: Input: n = 2, p = 7Output: 3 or 4Explanation: 3 and 4 both are square roots of 2 under modulo 7 because (3*3)
14 min read
Find Square Root under Modulo p | Set 2 (Shanks Tonelli algorithm)
Given a number ‘n’ and a prime ‘p’, find square root of n under modulo p if it exists. Examples: Input: n = 2, p = 113 Output: 62 62^2 = 3844 and 3844 % 113 = 2 Input: n = 2, p = 7 Output: 3 or 4 3 and 4 both are square roots of 2 under modulo 7 because (3*3) % 7 = 2 and (4*4) % 7 = 2 Input: n = 2, p = 5 Output: Square root doesn't exist We have di
15+ min read
Min operations to reduce N by multiplying by any number or taking square root
Given a number N, the task is to find the minimum value of N by applying below operations any number of times: Multiply N by any positive integerReplace N with sqrt(N), only if N is a perfect square. Examples: Input: N = 20 Output: 10Explanation: Multiply -&gt; 20 * 5 = 100 sqrt(100) = 10, which is the minimum value obtainable. Input: N = 5184 Outp
4 min read
Count numbers in range [L, R] that are divisible by square root of a number
Given two numbers L and R, the task is to find the count of all numbers in a given range [L, R] that are divisible by the square root of that number. The square root of a number is the value that, when multiplied by itself, gives the original number. Note: Here square root of a number represents the floor division. i.e, sqrt(4) = 2, sqrt(10) = 3, s
9 min read
Fast method to calculate inverse square root of a floating point number in IEEE 754 format
Given a 32-bit floating point number x stored in IEEE 754 floating point format, find the inverse square root of x, i.e., x-1/2.A simple solution is to do floating point arithmetic. Following is an example function. C/C++ Code #include &lt;bits/stdc++.h&gt; using namespace std; float InverseSquareRoot(float x) { return 1/sqrt(x); } int main() { cou
4 min read
Square root of a number by Repeated Subtraction method
The Repeated Subtraction method for finding the square root of a number is an interesting approach. It involves repeatedly subtracting consecutive odd numbers from the number until you reach zero or a negative number. The number of times you can subtract is the approximate square root of the original number. Given an integer N, the task is to find
4 min read
Inserting M into N such that m starts at bit j and ends at bit i | Set-2
Given two 32-bit numbers, N and M, and two-bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. Assuming index start from 0.Examples: a) N = 1024 (10000000000), M = 19 (10011), i = 2, j = 6 Output : 1100 (10001001100) b) N
10 min read
Count of 1-bit and 2-bit characters in the given binary string
Given two special characters, the first character can be represented by one bit which is 0 and the second character can be represented by two bits either 10 or 11. Now given a string represented by several bits. The task is to return the number of characters it represents. Note that the given string is always valid.Examples: Input: str = "11100" Ou
4 min read
Article Tags :
Practice Tags :