java 计算二进制,二进制搜索以计算平方根(Java)

I need help writing a program that uses binary search to recursively compute a square root (rounded down to the nearest integer) of an input non-negative integer.

This is what I have so far:

import java.util.Scanner;

public class Sqrt {

public static void main(String[] args) {

Scanner console = new Scanner(System.in);

System.out.print("Enter A Valid Integer: ");

int value = console.nextInt();

calculateSquareRoot(value);

}

public static int calculateSquareRoot(int value) {

while (value > 0) {

double sqrt = (int) Math.sqrt(value);

System.out.println(sqrt);

}

return -1;

}

}

The fact that it has to use binary search to compute the square root is the part that is confusing me. If anyone has any suggestions on how to do this, it would be greatly appreciated. Thank you

解决方案

Teh codez:

def sqrt(n):

low = 0

high = n+1

while high-low > 1:

mid = (low+high) / 2

if mid*mid <= n:

low = mid

else:

high = mid

return low

To understand it, just think of the loop invariant, namely:

lowlow <= n < highhigh

If you understand this code, writing a recursive version should be trivial.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值