java中不用Math.sqrt,实现开平方根的算法

17 篇文章 0 订阅
6 篇文章 0 订阅

前几天参加一个外企的面试,有一个笔试题,写出来共享一下,如有不对的地方,希望大家指点一下,谢谢

public class TestSqrt

{
public static void main(String[] args)
{
int num = 9;


System.out.println(sqrtMathod(num));
}


public static double sqrtMathod(int num)
{
double sqrtNum = -1;
boolean isFindSqrt = false;


// get int sqrt num
double tempSqrt = 0;
if (num > 0)
{
if (num == 1)
{
return 1;
}
else
{
for (int j = 0; j <= num / 2 + 1; j++)
{
if (j * j == num)
{
sqrtNum = j;
isFindSqrt = true;
break;
}
if (j * j > num)
{
tempSqrt = j - 1;
break;
}
}
}
}


if (!isFindSqrt)
{
sqrtNum = recuFindSqrt(num, tempSqrt, isFindSqrt, 1);
}


return sqrtNum;
}


private static double recuFindSqrt(int num, double sqrtValue, boolean isFindSqrt, double ac)
{
ac = ac * 10;
double tempSqrt = 0;
for (int i = 0; i < 10; i++)
{
tempSqrt = sqrtValue + i / ac;
if (tempSqrt * tempSqrt == num)
{
isFindSqrt = true;
sqrtValue = tempSqrt;
}
else if (tempSqrt * tempSqrt > num)
{
tempSqrt = add(sqrtValue, (i - 1) / ac);
sqrtValue = tempSqrt;
break;
}
}


Double temp = new Double(tempSqrt);
if (temp.toString().length() <= 16 && !isFindSqrt)
{
sqrtValue = recuFindSqrt(num, tempSqrt, isFindSqrt, ac);
}


return sqrtValue;
}


public static double add(double v1, double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();

}

}



  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值