Program for Square Root of Integer Last Updated : 19 Jun, 2025 Comments Improve Suggest changes Like Article Like Report Try it on GfG Practice Given a positive integer n, find its square root. If n is not a perfect square, then return floor of √n.Examples : Input: n = 4Output: 2Explanation: The square root of 4 is 2.Input: n = 11Output: 3Explanation: The square root of 11 lies in between 3 and 4 so floor of the square root is 3.Table of Content[Naive Approach] Using a loop - O(sqrt(n)) Time and O(1) Space[Expected Approach] Using Binary Search - O(log(n)) Time and O(1) Space [Alternate Approach] Using Built In functions - O(log(n)) Time and O(1) Space[Alternate Approach] Using Formula Used by Pocket Calculators - O(1) Time and O(1) Space[Naive Approach] Using a loop - O(sqrt(n)) Time and O(1) SpaceStart from 1 and square each number until the square exceeds the given number. The last number whose square is less than or equal to n is the answer. C++ #include <iostream> using namespace std; int floorSqrt(int n) { // Start iteration from 1 until the // square of a number exceeds n int res = 1; while(res*res <= n){ res++; } // return the largest integer whose // square is less than or equal to n return res - 1; } int main() { int n = 11; cout << floorSqrt(n); return 0; } C #include <stdio.h> int floorSqrt(int n) { // Start iteration from 1 until the // square of a number exceeds n int res = 1; while (res * res <= n) { res++; } // return the largest integer whose // square is less than or equal to n return res - 1; } int main() { int n = 11; printf("%d", floorSqrt(n)); return 0; } Java class GfG { static int floorSqrt(int n) { // Start iteration from 1 until the // square of a number exceeds n int res = 1; while (res * res <= n) { res++; } // return the largest integer whose // square is less than or equal to n return res - 1; } public static void main(String[] args) { int n = 11; System.out.println(floorSqrt(n)); } } Python def floorSqrt(n): # Start iteration from 1 until the # square of a number exceeds n res = 1 while res * res <= n: res += 1 # return the largest integer whose # square is less than or equal to n return res - 1 if __name__ == "__main__": n = 11 print(floorSqrt(n)) C# using System; class GfG { static int floorSqrt(int n) { // Start iteration from 1 until the // square of a number exceeds n int res = 1; while (res * res <= n) { res++; } // return the largest integer whose // square is less than or equal to n return res - 1; } static void Main() { int n = 11; Console.WriteLine(floorSqrt(n)); } } JavaScript function floorSqrt(n) { // Start iteration from 1 until the // square of a number exceeds n let res = 1; while (res * res <= n) { res++; } // return the largest integer whose // square is less than or equal to n return res - 1; } // Driver Code let n = 11; console.log(floorSqrt(n)); Output3[Expected Approach] Using Binary Search - O(log(n)) Time and O(1) Space The square of a number increases as the number increases, so the square root of n must lie in a sorted (monotonic) range.If a number's square is more than n, the square root must be smaller.If it's less than or equal to n, the square root could be that number or greater.Because of this pattern, we can apply binary search in the range 1 to n to efficiently find the square root. C++ #include <iostream> using namespace std; int floorSqrt(int n) { // Initial search space int lo = 1, hi = n; int res = 1; while(lo <= hi) { int mid = lo + (hi - lo)/2; // If square of mid is less than or equal to n // update the result and search in upper half if(mid*mid <= n) { res = mid; lo = mid + 1; } // If square of mid exceeds n, // search in the lower half else { hi = mid - 1; } } return res; } int main() { int n = 11; cout << floorSqrt(n); return 0; } C #include <stdio.h> int floorSqrt(int n) { // Initial search space int lo = 1, hi = n; int res = 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; // If square of mid is less than or equal to n // update the result and search in upper half if (mid * mid <= n) { res = mid; lo = mid + 1; } // If square of mid exceeds n, // search in the lower half else { hi = mid - 1; } } return res; } int main() { int n = 11; printf("%d", floorSqrt(n)); return 0; } Java class GfG { static int floorSqrt(int n) { // Initial search space int lo = 1, hi = n; int res = 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; // If square of mid is less than or equal to n // update the result and search in upper half if (mid * mid <= n){ res = mid; lo = mid + 1; } // If square of mid exceeds n, // search in the lower half else { hi = mid - 1; } } return res; } public static void main(String[] args) { int n = 11; System.out.println(floorSqrt(n)); } } Python def floorSqrt(n): # Initial search space lo = 1 hi = n res = 1 while lo <= hi: mid = lo + (hi - lo) // 2 # If square of mid is less than or equal to n # update the result and search in upper half if mid * mid <= n: res = mid lo = mid + 1 # If square of mid exceeds n, # search in the lower half else: hi = mid - 1 return res if __name__ == "__main__": n = 11 print(floorSqrt(n)) C# using System; class GfG { static int floorSqrt(int n) { // Initial search space int lo = 1, hi = n; int res = 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; // If square of mid is less than or equal to n // update the result and search in upper half if (mid * mid <= n) { res = mid; lo = mid + 1; } // If square of mid exceeds n, // search in the lower half else { hi = mid - 1; } } return res; } static void Main() { int n = 11; Console.WriteLine(floorSqrt(n)); } } JavaScript function floorSqrt(n) { // Initial search space let lo = 1, hi = n; let res = 1; while (lo <= hi) { let mid = lo + Math.floor((hi - lo) / 2); // If square of mid is less than or equal to n // update the result and search in upper half if (mid * mid <= n) { res = mid; lo = mid + 1; } // If square of mid exceeds n, // search in the lower half else { hi = mid - 1; } } return res; } // Driver Code let n = 11; console.log(floorSqrt(n)); Output3[Alternate Approach] Using Built In functions - O(log(n)) Time and O(1) Space We can directly use built in functions to find square root of an integer. C++ #include <iostream> #include <cmath> using namespace std; int floorSqrt(int n) { // Square root using sqrt function, it returns // the double value, which is casted to integer int res = sqrt(n); return res; } int main() { int n = 11; cout << floorSqrt(n); return 0; } C #include <stdio.h> #include <math.h> int floorSqrt(int n) { // Square root using sqrt function, it returns // the double value, which is casted to integer int res = sqrt(n); return res; } int main() { int n = 11; printf("%d", floorSqrt(n)); return 0; } Java class GfG { static int floorSqrt(int n) { // Square root using sqrt function, it returns // the double value, which is casted to integer int res = (int)Math.sqrt(n); return res; } public static void main(String[] args) { int n = 11; System.out.println(floorSqrt(n)); } } Python import math def floorSqrt(n): # Square root using sqrt function, it returns # the double value, which is casted to integer res = int(math.sqrt(n)) return res if __name__ == "__main__": n = 11 print(floorSqrt(n)) C# using System; class GfG { static int floorSqrt(int n) { // Square root using sqrt function, it returns // the double value, which is casted to integer int res = (int)Math.Sqrt(n); return res; } static void Main() { int n = 11; Console.WriteLine(floorSqrt(n)); } } JavaScript function floorSqrt(n) { // Square root using sqrt function, it returns // the double value, which is casted to integer let res = Math.floor(Math.sqrt(n)); return res; } // Driver Code let n = 11; console.log(floorSqrt(n)); Output3[Alternate Approach] Using Formula Used by Pocket Calculators - O(1) Time and O(1) SpaceThe idea is to use mathematical formula √n = e1/2 * log(n) to compute the square root of an integer n. Let's say square root of n is x: => x = √nSquaring both the sides: => x2 =nTaking log on both the sides:=> log(x2) = log(n) => 2*log(x) = log(n)=> log(x) = 1/2 * log(n)To isolate x, exponentiate both sides with base e:=> x = e1/2 * log(n)x is the square root of n: So, √n = e1/2 * log(n)Because of the way computations are done in computers in case of decimals, the result from the expression may be slightly less than the actual square root. Therefore, we will also consider the next integer after the calculated result as a potential answer. C++ #include <iostream> #include <cmath> using namespace std; int floorSqrt(int n) { // Calculating square root using mathematical formula int res = exp(0.5 * log(n)); // If square of res + 1 is less than or equal to n // then, it will be our answer if ((res + 1) * (res + 1) <= n) { res++; } return res; } int main() { int n = 11; cout << floorSqrt(n); return 0; } C #include <stdio.h> #include <math.h> int floorSqrt(int n) { // Calculating square root using mathematical formula int res = exp(0.5 * log(n)); // If square of res + 1 is less than or equal to n // then, it will be our answer if ((res + 1) * (res + 1) <= n) { res++; } return res; } int main() { int n = 11; printf("%d", floorSqrt(n)); return 0; } Java class GfG { static int floorSqrt(int n) { // Calculating square root using mathematical formula int res = (int)Math.exp(0.5 * Math.log(n)); // If square of res + 1 is less than or equal to n // then, it will be our answer if ((res + 1) * (res + 1) <= n) { res++; } return res; } public static void main(String[] args) { int n = 11; System.out.println(floorSqrt(n)); } } Python import math def floorSqrt(n): # Calculating square root using mathematical formula res = int(math.exp(0.5 * math.log(n))) # If square of res + 1 is less than or equal to n # then, it will be our answer if (res + 1) ** 2 <= n: res += 1 return res if __name__ == "__main__": n = 11 print(floorSqrt(n)) C# using System; class GfG { static int floorSqrt(int n) { // Calculating square root using mathematical formula int res = (int)Math.Exp(0.5 * Math.Log(n)); // If square of res + 1 is less than or equal to n // then, it will be our answer if ((long)(res + 1) * (res + 1) <= n) { res++; } return res; } static void Main() { int n = 11; Console.WriteLine(floorSqrt(n)); } } JavaScript function floorSqrt(n) { // Calculating square root using mathematical formula let res = Math.floor(Math.exp(0.5 * Math.log(n))); // If square of res + 1 is less than or equal to n // then, it will be our answer if ((res + 1) * (res + 1) <= n) { res++; } return res; } // Driver Code let n = 11; console.log(floorSqrt(n)); Output3 Comment More infoAdvertise with us Next Article Maximum and minimum of an array using minimum number of comparisons kartik Follow Improve Article Tags : Divide and Conquer Mathematical DSA Microsoft Amazon Snapdeal Accolite Ola Cabs Binary Search +5 More Practice Tags : AccoliteAmazonMicrosoftOla CabsSnapdealBinary SearchDivide and ConquerMathematical +4 More Similar Reads Divide and Conquer Algorithm Divide and Conquer algorithm is a problem-solving strategy that involves. Divide : Break the given problem into smaller non-overlapping problems.Conquer : Solve Smaller ProblemsCombine : Use the Solutions of Smaller Problems to find the overall result.Examples of Divide and Conquer are Merge Sort, Q 1 min read Introduction to Divide and Conquer Algorithm Divide and Conquer Algorithm is a problem-solving technique used to solve problems by dividing the main problem into subproblems, solving them individually and then merging them to find solution to the original problem. Divide and Conquer is mainly useful when we divide a problem into independent su 9 min read Dynamic Programming vs Divide-and-Conquer In this article Iâm trying to explain the difference/similarities between dynamic programming and divide and conquer approaches based on two examples: binary search and minimum edit distance (Levenshtein distance).The ProblemWhen I started to learn algorithms it was hard for me to understand the mai 12 min read Decrease and Conquer As divide-and-conquer approach is already discussed, which include following steps: Divide the problem into a number of subproblems that are smaller instances of the same problem. Conquer the sub problems by solving them recursively. If the subproblem sizes are small enough, however, just solve the 5 min read Advanced master theorem for divide and conquer recurrences The Master Theorem is a tool used to solve recurrence relations that arise in the analysis of divide-and-conquer algorithms. The Master Theorem provides a systematic way of solving recurrence relations of the form: T(n) = aT(n/b) + f(n) where a, b, and f(n) are positive functions and n is the size o 5 min read Some standard Divide and Conquer AlgorithmsWrite program to calculate pow(b, e)Given two numbers b and e, the task is to implement a function to compute b^e.Examples: Input: b = 3.00000, e = 5Output: 243.00000Input: b = 0.55000, e = 3Output: 0.16638Input: b = -0.67000, e = -7Output: -16.49971Table of Content[Naive Approach 1] Using Iteration - O(e) Time and O(1) Space[Naive Ap 10 min read Karatsuba algorithm for fast multiplication using Divide and Conquer algorithmGiven two binary strings that represent value of two integers, find the product of two strings. For example, if the first bit string is "1100" and second bit string is "1010", output should be 120.For simplicity, let the length of two strings be same and be n.A Naive Approach is to follow the proces 15+ min read Strassen's Matrix MultiplicationGiven two square matrices arr[][] and brr[][] of order n * n. Your task is to multiply both the matrices and find the resultant matrix.Examples:Input: arr[][] = [ [7, 8], [2, 9] ]brr[][] = [ [14, 5], [5, 18] ]Output: [ [138, 179], [73, 172] ]Input: arr[][] = [ [17, 4], [17, 16] ]brr[][] = [ [9, 2], 15+ min read Convex Hull using Divide and Conquer AlgorithmIn computational geometry, a convex hull is the smallest convex polygon that contains a given set of points. It is a fundamental concept with applications in various fields such as computer graphics, robotics, and image processing. Importance of Convex Hull:Convex hulls are important in computationa 15 min read Quickhull Algorithm for Convex HullGiven a set of points, a Convex hull is the smallest convex polygon containing all the given points. Input : points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}};Output : The points in convex hull are: (0, 0) (0, 3) (3, 1) (4, 4)Input : points[] = {{0, 3}, {1, 1}Output : Not P 14 min read Binary Search based problemsPeak Element in ArrayGiven an array arr[] where no two adjacent elements are same, find the index of a peak element. An element is considered to be a peak element if it is strictly greater than its adjacent elements. If there are multiple peak elements, return the index of any one of them.Note: Consider the element befo 12 min read Check for Majority Element in a sorted arrayGiven an array arr of N elements, A majority element in an array arr of size N is an element that appears more than N/2 times in the array. The task is to write a function say isMajority() that takes an array (arr[] ), arrayâs size (n) and a number to be searched (x) as parameters and returns true i 15+ min read K-th Element of Merged Two Sorted ArraysGiven two sorted arrays of sizes m and n respectively, the task is to find the element that would be at the k-th position in the final sorted array formed by merging these two arrays.Examples: Input: a[] = [2, 3, 6, 7, 9], b[] = [1, 4, 8, 10], k = 5Output: 6Explanation: The final sorted array is [1, 15+ min read Find the number of zeroesGiven an array of 1s and 0s which has all 1s first followed by all 0s. Find the number of 0s. Count the number of zeroes in the given array.Examples : Input: arr[] = {1, 1, 1, 1, 0, 0} Output: 2 Input: arr[] = {1, 0, 0, 0, 0} Output: 4 Input: arr[] = {0, 0, 0} Output: 3 Input: arr[] = {1, 1, 1, 1} O 12 min read Rotation Count in a Rotated Sorted arrayGiven an array arr[] having distinct numbers sorted in increasing order and the array has been right rotated (i.e, the last element will be cyclically shifted to the starting position of the array) k number of times, the task is to find the value of k.Examples: Input: arr[] = {15, 18, 2, 3, 6, 12}Ou 12 min read Unbounded Binary Search Example (Find the point where a monotonically increasing function becomes positive first time)Given a function 'int f(unsigned int x)' which takes a non-negative integer 'x' as input and returns an integer as output. The function is monotonically increasing with respect to the value of x, i.e., the value of f(x+1) is greater than f(x) for every input x. Find the value 'n' where f() becomes p 11 min read Median of two Sorted Arrays of Different SizesGiven two sorted arrays, a[] and b[], the task is to find the median of these sorted arrays. Assume that the two sorted arrays are merged and then median is selected from the combined array.This is an extension of Median of two sorted arrays of equal size problem. Here we handle arrays of unequal si 15+ min read The Painter's Partition Problem using Binary SearchGiven an array arr[] and k, where the array represents the boards and each element of the given array represents the length of each board. k numbers of painters are available to paint these boards. Consider that each unit of a board takes 1 unit of time to paint.The task is to find the minimum time 10 min read Some practice problems on Divide and Conquer algorithmProgram for Square Root of IntegerGiven a positive integer n, find its square root. If n is not a perfect square, then return floor of ân.Examples : Input: n = 4Output: 2Explanation: The square root of 4 is 2.Input: n = 11Output: 3Explanation: The square root of 11 lies in between 3 and 4 so floor of the square root is 3.Table of Co 11 min read Maximum and minimum of an array using minimum number of comparisonsGiven an array of size N. The task is to find the maximum and the minimum element of the array using the minimum number of comparisons.Examples:Input: arr[] = {3, 5, 4, 1, 9}Output: Minimum element is: 1 Maximum element is: 9Input: arr[] = {22, 14, 8, 17, 35, 3}Output: Minimum element is: 3 Maximum 15+ min read Find frequency of each element in a limited range array in less than O(n) timeGiven a sorted array arr[] of positive integers, the task is to find the frequency for each element in the array. Assume all elements in the array are less than some constant MNote: Do this without traversing the complete array. i.e. expected time complexity is less than O(n)Examples: Input: arr[] = 10 min read Tiling Problem - L ShapedGiven an nÃn board (where n = 2k and kâ¥1), with one missing cell, the task is to fill the remaining cells using L-shaped tiles. An L-shaped tile covers 3 cells in a 2x2 grid, with one cell missing. You need to tile the entire board using the L-shaped tiles, ensuring that the missing cell remains unc 15+ min read Count Inversions of an ArrayGiven an integer array arr[] of size n, find the inversion count in the array. Two array elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j.Note: Inversion Count for an array indicates that how far (or close) the array is from being sorted. If the array is already sorted 15+ min read The Skyline Problem | Set-1Given n rectangular buildings in a 2-dimensional city, compute the skyline of these buildings, eliminating hidden lines. The main task is to view buildings from a side and remove all sections that are not visible. All buildings share a common bottom and every building is represented by a triplet (le 13 min read Search in a Row-wise and Column-wise Sorted 2D Array using Divide and Conquer algorithmGiven an n x n matrix, where every row and column is sorted in increasing order. Given a key, how to decide whether this key is in the matrix. Input: x = 62, mat[][] = [[3, 30, 38], [20, 52, 54], [35, 60, 69]]Output: falseExplanation: 62 is not present in the matrix.Input: x = 30, mat[][] = [[3, 30] 7 min read Allocate Minimum PagesGiven an array arr[] and an integer k, where arr[i] denotes the number of pages of a book and k denotes total number of students. All the books need to be allocated to k students in contiguous manner, with each student getting at least one book.The task is to minimize the maximum number of pages all 15+ min read Like