• Courses
  • Tutorials
  • DSA
  • Data Science
  • Web Tech
October 28, 2022 |1.7K Views

C program to find square root of a negative number

  Share  1 Like
Description
Discussion

In this video, we will write a C Program to find the square root of a negative number

Here, given a negative number N, the task is to write a C program to find the square root of that given number N.

Examples:

Input: N = -9
Output: 3i

Here we see 2 different methods for finding the square root of a negative number:

  1. Using binary search
  2. Using Sqrt(number)

Using binary search:

Step 1: Firstly take the abs(number).
Step 2: Now, initialized start = 0 and end = number.  
Step 3: Calculate the mid value by using mid = (start+end)/2.
Step 4: If mid*mid = Number, then store mid in ans and exit the loop.
Step 5: If mid*mid < Number, then  ans = start  and start = mid+ 1;.
Step 6:If mid*mid > Number, then end = mid-1;.
Step 7: We will get an integral part, and we will find the fractional part.
Step 8: initialize the increment by 0.1 and iteratively calculate the fractional part up to 5 decimal places in ans.
Step 9: For each iteration change increment to 1/10th of its previous value.
Step 10: Finally return the ans and print ans i.


Using Sqrt(Number):
In the second method, we use the inbuilt sqrt() function to return the sqrt of the negative number N.

Apart from that, we will see the Time and Space complexity of both methods:

Using binary search:
Time Complexity: Sqrt(N), Space Complexity: O(1)

Using Sqrt(number):
Time Complexity: Sqrt(N), Space Complexity:O(1)