题解 | #平方根#
平方根
https://ac.nowcoder.com/acm/problem/22003
方法一:
```// 牛顿送代法
#include<bits/stdc++.h>
using namespace std;
int n;
double f( int m )
{
double last = m;
double ans = m;
ans = ( ans + m / ans ) / 2;
while( abs( ans - last ) > 0.0001 )
{
last = ans;
ans = ( ans + m / ans ) / 2;
}
return ans;
}
int main()
{
cin >> n;
cout << int(f(n)) << endl;
}
法二:
```// 二分法
#include<bits/stdc++.h>
using namespace std;
long long n, c, cnt, st;
int main()
{
cin >> c;
int l = 0, r = c;
while( l < r )
{
int mid = l + r >> 1;
if( mid * mid > c )
{
r = mid - 1;
}
else if( mid * mid < c )
{
l = mid + 1;
}
else
{
cout << int(mid);
return 0;
}
}
if( r > l )
{
if( r * l < c && ( r + 1 ) * ( r + 1 ) < c )
{
cout << int( r + 1 );
}
else if( r * r < c && ( r + 1 ) * ( r + 1 ) > c )
{
cout << int(r);
}
else if( r * r > c )
{
cout << int( r - 1 );
}
else
{
cout << int(r);
}
}
else
{
if( l * l < c && ( l + 1 ) * ( l + 1 ) < c )
{
cout << int( l + 1 );
}
else if( l * l < c && ( l + 1 ) * ( l + 1 ) > c )
{
cout << int(l);
}
else if( l * l > c )
{
cout << int( l - 1 );
}
else
{
cout << int(l);
}
}
return 0;
}
法三:
``` // 约翰 - 卡马克算法
#include<bits/stdc++.h>
using namespace std;
int n;
float f(float x)
{
float xhalf = 0.5f * x;
int i = *(int*) & x;
i = 0x5f375a86 - ( i >> 1 );
x = *(float*) & i;
x = x * ( 1.5f - xhalf * x * x );
x = x * ( 1.5f - xhalf * x * x );
x = x * ( 1.5f - xhalf * x * x );
return 1 / x;
}
int main()
{
cin >> n;
cout << int(f(n)) << endl;
return 0;
}