Redian新闻
>
请问给一个整数,如何返回他的平方根?
avatar
请问给一个整数,如何返回他的平方根?# JobHunting - 待字闺中
a*n
1
谢谢。
就是sqrt的实现。
avatar
p*2
2
不是说binary search吗?
avatar
f*t
3
牛顿迭代法,任取一a,然后不断a = (a + n/a)/2循环,直到某个精度。
double sqrt(int n)
{
if(n <= 0)
return 0;

double ans = (double)n / 2.0;
int round = 0;
const double epsilon = 0.00001;
while(true) {
round++;
ans = (ans + (double)n / ans) / 2;
double diff = ans * ans - (double)n;
if(diff < 0)
diff = -diff;
if(diff < epsilon)
break;
}

printf("Calculated %d rounds\n", round);

return ans;
}
avatar
B*e
4
嘿嘿, 有笔和纸, 谁还记得怎么算出一个数的开方?
譬如一分种之内, 算出(2011)^(0.5), 精确到小数点后第三位.
小时候学过的 ...

【在 a********n 的大作中提到】
: 谢谢。
: 就是sqrt的实现。

avatar
d*t
5
我早都忘记了,你告诉我一下吧。

【在 B*****e 的大作中提到】
: 嘿嘿, 有笔和纸, 谁还记得怎么算出一个数的开方?
: 譬如一分种之内, 算出(2011)^(0.5), 精确到小数点后第三位.
: 小时候学过的 ...

avatar
a*h
6
格式像算除法,
2011 是“被除数”, 两位一分,
20 > 4×4 <5*5, 所以第一位是 4,
余数加11 是 411, 第一位的结果 4 × 20 加上 a, 计算 8a*a < 411, a=4 是第
二位,
类推。
avatar
a*n
7
谢,这个实现写的挺不错。

【在 f*******t 的大作中提到】
: 牛顿迭代法,任取一a,然后不断a = (a + n/a)/2循环,直到某个精度。
: double sqrt(int n)
: {
: if(n <= 0)
: return 0;
:
: double ans = (double)n / 2.0;
: int round = 0;
: const double epsilon = 0.00001;
: while(true) {

avatar
y*g
8
这种题目一般考点不是这个,需要数值知识的会考其他东西

【在 f*******t 的大作中提到】
: 牛顿迭代法,任取一a,然后不断a = (a + n/a)/2循环,直到某个精度。
: double sqrt(int n)
: {
: if(n <= 0)
: return 0;
:
: double ans = (double)n / 2.0;
: int round = 0;
: const double epsilon = 0.00001;
: while(true) {

avatar
z*u
9
平方根这个题目应该是给定一个整数,找和它的平方根最接近的整数吧
用二分查找

【在 y*******g 的大作中提到】
: 这种题目一般考点不是这个,需要数值知识的会考其他东西
avatar
d*y
10
using binary search
public double sqrt(int n)
{
if(n<=0)
return 0;
int low = 0;
int high = n + 1;
while((high - low) > 1)
{
middle = (high + low)/2;
if(middle*middle<=n)
low = middle;
else
high = middle;
}
}
avatar
d*y
11
using binary search
public double sqrt(int n)
{
if(n<=0)
return 0;
int low = 0;
int high = n + 1;
while((high - low) > 1)
{
middle = (high + low)/2;
if(middle*middle<=n)
low = middle;
else
high = middle;
}
return low;
}
avatar
a*n
12
如果给的数字开不了方,这个code没结果吧。

【在 d******y 的大作中提到】
: using binary search
: public double sqrt(int n)
: {
: if(n<=0)
: return 0;
: int low = 0;
: int high = n + 1;
: while((high - low) > 1)
: {
: middle = (high + low)/2;

avatar
d*y
13
I didn't test my code. just to practice.Any comments will be appreciated
I think you may know the concept of this type of question.
e.g. if n = 100 you choose 0 - 101 boundary. 50 * 50 > n so the boundary
turns into 0 - 50 keep doing this.
BTW : what is Gover's security clearance and DoD secret security clearance?
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。