 Open in App
Not now

# Python Program To Find Square Root Of Given Number

• Last Updated : 19 Mar, 2023

Given an integer X, find its square root. If X is not a perfect square, then return floor(√x).

Examples :

Input: x = 4
Output: 2
Explanation: The square root of 4 is 2.

Input: x = 11
Output: 3
Explanation:  The square root of 11 lies in between 3 and 4 so floor of the square root is 3.

Recommended Practice

Naive Approach: To find the floor of the square root, try with all-natural numbers starting from 1. Continue incrementing the number until the square of that number is greater than the given number.

Follow the steps below to implement the above idea

1. Create a variable (counter) i and take care of some base cases, (i.e when the given number is 0 or 1).
2. Run a loop until i*i <= n, where n is the given number. Increment i by 1.
3. The floor of the square root of the number is i – 1

Below is the implementation of the above approach:

## Python3

 `# Python3 program to find floor(sqrt(x)`   `# Returns floor of square root of x`     `def` `floorSqrt(x):`   `    ``# Base cases` `    ``if` `(x ``=``=` `0` `or` `x ``=``=` `1``):` `        ``return` `x`   `    ``# Starting from 1, try all numbers until` `    ``# i*i is greater than or equal to x.` `    ``i ``=` `1` `    ``result ``=` `1` `    ``while` `(result <``=` `x):`   `        ``i ``+``=` `1` `        ``result ``=` `i ``*` `i`   `    ``return` `i ``-` `1`     `# Driver Code` `x ``=` `11` `print``(floorSqrt(x))`

## C++

 `#include ` `using` `namespace` `std;`   `// Returns floor of square root of x` `int` `floorSqrt(``int` `x)` `{` `    ``// Base cases` `    ``if` `(x == 0 || x == 1)` `        ``return` `x;`   `    ``// Starting from 1, try all numbers until` `    ``// i*i is greater than or equal to x.` `    ``int` `i = 1, result = 1;` `    ``while` `(result <= x)` `    ``{` `        ``i++;` `        ``result = i * i;` `    ``}` `    ``return` `i - 1;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `x = 11;` `    ``cout << floorSqrt(x) << endl;` `    ``return` `0;` `}`

Output

`3`

Complexity Analysis:

• Time Complexity: O(√X). Only one traversal of the solution is needed, so the time complexity is O(√X).
• Auxiliary Space: O(1).

## Square root an integer using Binary search:

The idea is to find the largest integer i whose square is less than or equal to the given number. The values of i * i is monotonically increasing, so the problem can be solved using binary search.

Below is the implementation of the above idea:

1. Base cases for the given problem are when the given number is 0 or 1, then return X;
2. Create some variables, for storing the lower bound say l = 0, and for upper bound r = X / 2 (i.e, The floor of the square root of x cannot be more than x/2 when x > 1).
3. Run a loop until l <= r, the search space vanishes
4. Check if the square of mid (mid = (l + r)/2 ) is less than or equal to X, If yes then search for a larger value in the second half of the search space, i.e l = mid + 1, update ans = mid
5. Else if the square of mid is more than X then search for a smaller value in the first half of the search space, i.e r = mid – 1
6. Finally, Return the ans

Below is the implementation of the above approach:

## Python3

 `# Python 3 program to find floor(sqrt(x)`   `# Returns floor of square root of x`     `def` `floorSqrt(x):`   `    ``# Base cases` `    ``if` `(x ``=``=` `0` `or` `x ``=``=` `1``):` `        ``return` `x`   `    ``# Do Binary Search for floor(sqrt(x))` `    ``start ``=` `1` `    ``end ``=` `x``/``/``2` `    ``while` `(start <``=` `end):` `        ``mid ``=` `(start ``+` `end) ``/``/` `2`   `        ``# If x is a perfect square` `        ``if` `(mid``*``mid ``=``=` `x):` `            ``return` `mid`   `        ``# Since we need floor, we update` `        ``# answer when mid*mid is smaller` `        ``# than x, and move closer to sqrt(x)` `        ``if` `(mid ``*` `mid < x):` `            ``start ``=` `mid ``+` `1` `            ``ans ``=` `mid`   `        ``else``:`   `            ``# If mid*mid is greater than x` `            ``end ``=` `mid``-``1`   `    ``return` `ans`     `# driver code` `x ``=` `11` `print``(floorSqrt(x))`

## C++

 `#include ` `using` `namespace` `std;`   `// Returns floor of square root of x` `int` `floorSqrt(``int` `x)` `{` `    ``// Base cases` `    ``if` `(x == 0 || x == 1)` `        ``return` `x;`   `    ``// Do Binary Search for floor(sqrt(x))` `    ``int` `start = 1, end = x/2, ans;` `    ``while` `(start <= end)` `    ``{` `        ``int` `mid = (start + end) / 2;`   `        ``// If x is a perfect square` `        ``if` `(mid*mid == x)` `            ``return` `mid;`   `        ``// Since we need floor, we update` `        ``// answer when mid*mid is smaller` `        ``// than x, and move closer to sqrt(x)` `        ``if` `(mid * mid < x)` `        ``{` `            ``start = mid + 1;` `            ``ans = mid;` `        ``}` `        ``else` `        ``{` `            ``// If mid*mid is greater than x` `            ``end = mid - 1;` `        ``}` `    ``}` `    ``return` `ans;` `}`   `// driver code` `int` `main()` `{` `    ``int` `x = 11;` `    ``cout << floorSqrt(x) << endl;` `    ``return` `0;` `}  `

Output

`3`

Complexity Analysis:

• Time Complexity: O(log(X)).
• Auxiliary Space: O(1).

## Square root an integer using built-in functions:

Below is the implementation for finding the square root using the built-in function.

## Python3

 `def` `countSquares(x):` `    ``sqrt ``=` `x``*``*``0.5` `    ``result ``=` `int``(sqrt)` `    ``return` `result`     `x ``=` `9` `print``(countSquares(x))`

## C++

 `#include ` `#include ` `using` `namespace` `std;`   `int` `countSquares(``int` `x) {` `    ``double` `sqrt` `= ``pow``(x, 0.5);` `    ``int` `result = ``int``(``sqrt``);` `    ``return` `result;` `}`   `int` `main() {` `    ``int` `x = 9;` `    ``cout << countSquares(x) << endl;` `    ``return` `0;` `}`

Output

`3`

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

#### Use numpy.sqrt() :

To find the square root of a number using numpy, you can use the numpy.sqrt() function. This function takes in a number or an array of numbers and returns the square root of each element.

Here is an example of how you can use numpy.sqrt() to find the square root of a number:

## Python3

 `import` `numpy as np`   `# Find the square root of 9` `sqrt_9 ``=` `np.sqrt(``9``)` `print``(sqrt_9)  ``# Output: 3.0`   `# Find the square root of a list of numbers` `numbers ``=` `[``4``, ``9``, ``16``, ``25``]` `sqrt_numbers ``=` `np.sqrt(numbers)` `print``(sqrt_numbers)  ``# Output: [2.0 3.0 4.0 5.0]` `#This code is contributed by Edula Vinay Kumar Reddy`

## C++

 `#include ` `#include ` `#include ` `using` `namespace` `std;`   `int` `main() {` `    ``// Find the square root of 9` `    ``double` `sqrt_9 = ``sqrt``(9);` `    ``cout << sqrt_9 << endl;  ``// Output: 3.0`   `    ``// Find the square root of a list of numbers` `    ``vector<``double``> numbers = {4, 9, 16, 25};` `    ``vector<``double``> sqrt_numbers(numbers.size());` `    ``for` `(``int` `i = 0; i < numbers.size(); i++) {` `        ``sqrt_numbers[i] = ``sqrt``(numbers[i]);` `    ``}` `    ``for` `(``int` `i = 0; i < sqrt_numbers.size(); i++) {` `        ``cout << sqrt_numbers[i] << ``" "``;` `    ``}` `    ``cout << endl;  ``// Output: 2 3 4 5` `    ``return` `0;` `}`

Note that numpy.sqrt() returns a numpy array if the input is an array, and a single value if the input is a single number.

The time complexity of the code you provided is O(1) for the first example, and O(n) for the second example, where n is the length of the input list. The Auxiliary Space is O(1) for both examples.

The time complexity of the np.sqrt() function is O(1) for a single input and O(n) for an array of inputs, because it involves computing the square root of the input values. The time complexity is constant for a single input and linear in the size of the array for an array of inputs.

The space complexity of the np.sqrt() function is O(1) for both a single input and an array of inputs, because it does not use any additional data structures and the space it uses is independent of the input size. The function returns a single value for a single input and an array of values for an array of inputs.

There can be many ways to solve this problem. For example, the Babylonian Method is one way.

Please refer complete article on Square root of an integer for more details!

My Personal Notes arrow_drop_up
Related Articles