Table of contents
1.
Introduction
2.
What is sqrt() in C++?
3.
Syntax of sqrt() in C++
4.
Parameters of sqrt() in C++
5.
Return Value of sqrt() in C++
6.
Exceptions for sqrt() in C++
7.
Example of sqrt() Function in C++
8.
Brute Force Approach to find sqrt() in C++
8.1.
Steps of Algorithm to find sqrt() in C++
8.2.
Implementation in C++
9.
Optimized Approach - 1
9.1.
Steps of Algorithm
9.2.
Implementation in C++
10.
Optimized Approach - 2
10.1.
Steps of Algorithm
10.2.
Implementation in C++
11.
Frequently Asked Questions
11.1.
What library is sqrt in C++?
11.2.
How to get square root in C++ without sqrt?
11.3.
What is the output datatype for the sqrt() function?
12.
Conclusion
Last Updated: Oct 8, 2024
Easy

sqrt() in C++

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

he sqrt() function in C++ is a part of the <cmath> library and is used to calculate the square root of a given number. It plays a crucial role in various mathematical computations and algorithms. Understanding how to implement and utilize this function is essential for developers and programmers working with numerical data and mathematical models in their C++ applications.

sqrt() in C++

Let’s discuss how we can find the square root of a number in C++.

What is sqrt() in C++?

The `sqrt()` function in C++ is part of the `<cmath>` library, used to compute the square root of a non-negative number. It takes a double type argument and returns the square root as a double. If the argument is negative, it typically returns NaN (Not a Number). This function is essential in mathematical calculations and applications requiring square root computations.

Syntax of sqrt() in C++

double sqrt(double x);

Parameters of sqrt() in C++

x: A non-negative number (of type double) whose square root is to be calculated.

Return Value of sqrt() in C++

The sqrt() function returns the square root of the specified non-negative number as a double. If the input is negative, it generally returns NaN (Not a Number).

Exceptions for sqrt() in C++

  • Negative Input: Passing a negative number results in NaN (Not a Number), as square roots of negative numbers are undefined in the realm of real numbers.
     
  • Infinity: If the input is positive or negative infinity, the result is also infinity (positive or negative, respectively).
     
  • Precision Issues: Due to floating-point arithmetic limitations, extremely small or large values may yield inaccurate results.
     
  • Library Dependency: Ensure the <cmath> or <math.h> header is included, as sqrt() is defined in these libraries. Missing the header can lead to compilation errors.
     
  • Domain Error: If a negative value is passed, sqrt() may cause a domain error, returning NaN.
     
  • Error Handling: Users can check for NaN to handle such cases gracefully in their programs.

Example of sqrt() Function in C++

Here’s a simple example demonstrating the use of the sqrt() function in C++:

#include <iostream>
#include <cmath>
int main() {
   double number = 16.0;
   double result = sqrt(number);
   std::cout << "The square root of " << number << " is " << result << std::endl;
   return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

The square root of 16 is 4


In this example, the program calculates and prints the square root of 16, which is 4.

Brute Force Approach to find sqrt() in C++

This approach is very simple to implement. We incrementally square all the natural numbers starting from 1 until we get the input number or something greater. This approach only gives integers as output. So, the square root of 66 would be 8, also called the floor value of the square root.

Steps of Algorithm to find sqrt() in C++

  1. First, we create the counter variable i. We take care of some rare cases, like when the given number is 1 or 0.
  2. We initialise a loop that checks if i<= n (the variable containing the given number). We increment i by 1 until the loop ends.
  3. The value of i-1 at the end is the required square root of the given number.

Implementation in C++

#include<bits/stdc++.h>

using namespace std;
 
int sqrt(int input) {
    if (input == 0 || input == 1)                   // Rare cases
        return input;                               // Output

    int i = 1, check = 1;
    while (check <= input) {
      i++;
      check = i * i;
    }
    return i - 1;                                   // Output
}

int main() {
    int input;
    cout << "Enter the number: ";
    cin >> input;
    cout << "The square root is " << sqrt(input) << endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

Enter the number: 92
The square root is 9

 

Time Complexity: O(√ n)

Explanation: As the program traverses the solution only once, the time complexity is O(√ n)

 

Space Complexity: O(1)

Explanation: In this approach, constant extra space is needed, so the space complexity is O(1)

You can try by yourself with the help of online C++ Compiler.

Optimized Approach - 1

In this approach, we use binary search to find the largest integer whose square is less than or equal to the given number. This approach also gives the floor value for square roots that are not integers.

Steps of Algorithm

  1. We initialise the counter and take care of some rare cases, just like the last approach.
  2. ranstr, ranend and ranmid are initialised to set the range of values we have to check and store its midpoint. Initialise ans to store the answer.
  3. Start a loop from ranstr to ranend (ranstr <= ranend). This range is the search space.
  4. We check if the ranmid (= ranstr + ranend / 2) is less than or equal to input. If it is, we check for another value in the upper half of the search space. Here, ranstr = ranmid + 1 and ans = ranmid.
  5. If ranmid is greater than input, the new range is the lower half of the previous one. Here, ranend = ranmid - 1.
  6. In the end, we return ans as the answer.

Implementation in C++

#include<bits/stdc++.h>
using namespace std;

int sqrt(int input) {
    if (input == 0 || input == 1)                // Rare cases
        return input;                            // Output

    int ranstr = 1, ranend = input/2, ans;
    while (ranstr <= ranend) {
        int ranmid = (ranstr + ranend) / 2;
 
        int sqr = ranmid * ranmid;
        if (sqr == input)                        // If input is a perfect square
            return ranmid;
       
        if (sqr <= input) {
            ranstr = ranmid + 1;                 // Since sqr is smaller, we will start in the upper half
            ans = ranmid;
        }
        else                                     // If ranmid*ranmid is greater than input
            ranend = ranmid - 1;
    }
    return ans;                        
}

int main() {
    int input;
    cout << "Enter the number: ";
    cin >> input;
    cout << "The square root is " << sqrt(input) << endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

Enter the number: 157
The square root is 12

 

Time Complexity: O(log n)

Explanation: In this approach, we used the binary tree, which has a time complexity of O(log n)

 

Space Complexity: O(1)

Explanation: In this approach, constant extra space is needed, so the space complexity is O(1)

Optimized Approach - 2

This time we use a function from C++’s vast and handy library. The sqrt() function can give us the exact square root of any number up to 7 decimal places.

Steps of Algorithm

  1. This is the most straightforward approach yet. Store the given variable in the variable input.
  2. Process it through the sqrt() function. This gives the value of the square root. Then display the result to the user.

Implementation in C++

#include<bits/stdc++.h>
using namespace std;

int main() {
    double input;
    cout << "Enter the number: ";
    cin >> input;
    cout << "The square root is " << sqrt(input) << endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

Enter the number: 66
The square root is 8.12404

 

Time Complexity: O(log n)

Explanation: As the sqrt() function is used, the time complexity is O(log n)

 

Space Complexity: O(1)

Explanation: In this approach, constant extra space is needed, so the space complexity is O(1)

Must Read Swap Two Numbers Without Using Third Variable

Frequently Asked Questions

What library is sqrt in C++?

The sqrt() function in C++ is defined in the <cmath> library. This library provides mathematical functions, including square root, trigonometric functions, and logarithmic functions, enabling advanced mathematical computations in your programs.

How to get square root in C++ without sqrt?

To compute the square root in C++ without using the sqrt() function, you can utilize the exponentiation operator **. For example, to find the square root of a number x, you can calculate it as x^(0.5) or pow(x, 0.5) from the <cmath> library.

What is the output datatype for the sqrt() function?

The sqrt() function in C++ returns a value of the double data type, which represents a floating-point number. This allows it to handle not only integer results but also decimal values when dealing with the square roots of non-perfect squares. Using double ensures that the result has a higher degree of precision, which is important for mathematical computations that require accurate decimal values.

Also Read - Strong number in c

Conclusion

In conclusion, we discussed the problem statement and different ways to solve the problems. For every approach, we discussed the algorithm and complexities. We eventually saw how each of the methods are different from the other.

Also check out this article - 

Refer to our guided paths on Code360 to upskill yourself!

Live masterclass