Writing Your Own Sqrt Function

Abdullah Afzal
2 min readAug 27, 2022
Photo by Volkan Olmez on Unsplash

Function Input and Output :

Before talking about the function's algorithm, clarify the function’s input and output. The function takes an integer number as input and returns an integer number which is the square root of the input Number.

Basically, the requirement is to give the square root of the input number in integer form, if it is in float (decimal) then we will floor the value and make it an integer.

Algorithm of Function :

There are many ways to write the program for calculating the square root of an integer.

The approach I used is simple and easy to understand but only works for the function with such requirements as mentioned above.

The approach is the same as in Binary Search Approach. We just do a binary search for the number in the numbers less the input numbers. We know the square root of the number cannot be greater than half of the number. (e.g if N is the input number, the square root can’t be greater than N/2)

So we will binary search for the number, the square of which is equal to the input number (N). if we don’t find any such number we will return the number the square of which is close to the input number.

Code of the Function :

--

--

Abdullah Afzal
Abdullah Afzal

Written by Abdullah Afzal

A student, always trying to look up for cool things and do something creative.