DEV Community

Lalit Kumar
Lalit Kumar

Posted on

How to find square root in C++ without using sqrt function?

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.

Methods

  • Log method
  • Power algorithm ##Illustrations All the methods are explained with illustratoins below.

title: "How to find square root in C++ without using sqrt function?"
tags: cpp

canonical_url: https://kodlogs.com/blog/1920/how-to-find-square-root-in-c-without-using-sqrt-function

Log method

Below is one simple log method that can be used:

// C++ program to show finding 

// square root of a number using log2() 

#include<bits/stdc++.h> 

double squareRoot(double n) 

{ 

    return pow(2, 0.5*log2(n)); 

} 

int main(void) 

{ 

    double n = 12; 

    printf("%lf ", squareRoot(n)); 

    return 0; 

} 
Enter fullscreen mode Exit fullscreen mode

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.

Power algorithm

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:

#include <math.h>

double pow(double x, double y);
Enter fullscreen mode Exit fullscreen mode

Another one

Example of how to find square root using double/ power function is shown below:

x = int(input())

 import math 

print(pow(x, 0.5))

 or

print(x**0.5)
Enter fullscreen mode Exit fullscreen mode

Note: if the value of x above is negative, the return value is NaN

Hope this helps.

Top comments (0)