Several ways can find or calculate square roots in C++ programming without using sqrt function. However, to get the answer, several iterations may be required for some large numbers which might appear inconveniencing.
- Log method
- Power algorithm
All the methods are explained with illustratoins below.
Below is one simple log method that can be used:
// C++ program to show finding
// square root of a number using log2()
double squareRoot(double n)
return pow(2, 0.5*log2(n));
double n = 12;
printf("%lf ", squareRoot(n));
The declarations of all variables must be made which means the programmer has to specify the value of log and the value of n whose square root needs to be found.
Below is the power algorithm. The algorithm raises the value of x ^y i.e. x raised to power of y. The power syntax is:
double pow(double x, double y);
Example of how to find square root using double/ power function is shown below:
x = int(input())
Note: if the value of x above is negative, the return value is NaN
Hope this helps.