Algorithm to find square root [loop]

Give you a positive integer and find the value of its positive square root. If the value of its positive square root is not an integer, then take the integer part. Library functions are not allowed.

Example 1:

Input: 9

Output: 3

Example 2:

Input: 10

Output: 3

Algorithm 1: Find the square root by dichotomy, which is similar to the idea of ​​searching in half, constantly narrowing the search interval, when i^2 >n &&(i-1)^2<n, the arithmetic square root is i-1;

double sqrt1(double x) {
    
    
	double EPS = 0.00000001;
	double low = 0.0;
	double high = x;
	double mid = (low + high) / 2;
	while ((high - low) > EPS) {
    
    
		if (mid * mid > x) {
    
    
			high = mid;
		}
		else {
    
    
			low = mid;
		}
		mid = (high + low) / 2;
	}
	return mid;
}

Algorithm 2: Use loops to traverse sequentially

int MySqrt(int n)  

{
    
      
     int i;  

      for(i=0;i*i<=n;i++)  ;  

     return i-1;  
  }  

Guess you like

Origin blog.csdn.net/Gunanhuai/article/details/109262390