设计一个函数int sqrt(int x),求 一个数的平方根。如果此数不是完全平方数,则输出最大可以是谁的平方。
eg:输入1 2 3 4 5 6 7 8 9,输出1 1 1 2 2 2 2 2 3
方法一:可以采取二分查找,代码如下
#include<stdio.h>
int sqrt(int x){
int low=1,high=x,mid,res,tmp;
while(low<high){
mid=(low+high)/2;
tmp=mid*mid;
if(tmp==x)
return mid;
else if(tmp>x)
high=mid-1;
else
low=mid+1;
}
mid=(low+high)/2;
tmp=mid*mid;
if(tmp>x)
mid--;
res=mid;
return res;
}
int main(){
int x;
while(scanf("%d",&x) != EOF){
printf("%d\n",sqrt(x));
}
return 0;
}
方法二:
采取牛顿迭代法
#include<stdio.h>
#include<math.h>
int sqrt(int x){
int res=x,tmp;
tmp=abs(res*res-x);
while(tmp>0.00001){
res=(res+x/res)/2;
tmp=abs(res*res-x);
}
return res;
}
int main(){
int x;
while(scanf("%d",&x) != EOF){
printf("%d\n",sqrt(x));
}
return 0;
}
参考网址
http://www.cnblogs.com/xkfz007/archive/2012/05/15/2502348.html