Last Updated: 27 Nov, 2020

Square Root of a number

Easy
Asked in companies
SamsungAmazonMicrosoft

Problem statement

You are given a positive integer ‘n’.


Your task is to find and return its square root. If ‘n’ is not a perfect square, then return the floor value of sqrt(n).


Example:
Input: ‘n’ = 7

Output: 2

Explanation:
The square root of the number 7 lies between 2 and 3, so the floor value is 2.


Input Format:
The first line of input contains the Integer ‘n’.


Output Format:
The output contains an integer denoting the square root of ‘n’.


Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.

Approaches

01 Approach

The idea is to iterate through all numbers and check.

 

Algorithm :

 

  • Take care of the corner case, N = 0.
  • Take a variable ‘ans’ that stores the square root of the given number, initialize it to 1.
  • Run a loop while the square of ‘ans’ is less than or equal to the given number ‘N’.
    • Increment ‘ans’ by 1.
  • Return ‘ans’-1.

02 Approach

The idea is to find the largest integer number whose square is less than or equal to the given number ‘N’.

 

Algorithm :

 

  • Take care of corner cases when ‘N’ is equal to ‘0’ or ‘1’ return ‘N’
  • Take a variable ‘low’ initialized to 2 and a variable ‘high’ initialized to ‘N’.
  • Take a variable ‘mid’ that stores the mid of ‘low’ and ‘high’ value.
  • Run a while loop until ‘low’ is less than ‘high’.
    • Find mid as ‘low’ + ( ‘low’ + ‘high’ ) / 2.
    • If (mid’ * ‘mid’)  is less than equal to ‘N’, update ‘low’ =  mid + 1.
    • Else, update ‘high’ equal to ‘mid’.
  • Return  ‘low’ - 1.