對於一個賦值,我必須創建一個方法,使用二分查找找到一個整數的平方根,如果它不是一個平方數,它應該返回一個整數s,使得s * s < =數字(對於15,它會返回3)。我到目前爲止的代碼是二進制搜索平方根[作業]
public class BinarySearch {
/**
* Integer square root Calculates the integer part of the square root of n,
* i.e. integer s such that s*s <= n and (s+1)*(s+1) > n
* requires n >= 0
*
* @param n number to find the square root of
* @return integer part of its square root
*/
private static int iSqrt(int n) {
int l = 0;
int r = n;
int m = ((l + r + 1)/2);
// loop invariant
while (Math.abs(m * m - n) > 0) {
if ((m) * (m) > n) {
r = m;
m = ((l + r + 1)/2);
} else {
l = m;
m = ((l + r + 1)/2);
}
}
return m;
}
public static void main(String[] args) {
//gets stuck
System.out.println(iSqrt(15));
//calculates correctly
System.out.println(iSqrt(16));
}
}
而這將返回正方形數字的正確數字,但獲取其他整數的無限循環。我知道問題在於時間條件,但由於數字變得越大,方形數字之間的差距越大,所以我無法弄清楚應該放什麼(所以我不能只是說差距必須低於一個門檻)。如果這個練習有幫助,那麼這個練習是關於不變量的(因此它是以這種方式建立的)。謝謝。
使用只有int的問題是,你需要在算法中的錯誤marge變得越來越大,你想知道的數字的平方根。 – 2014-12-07 16:22:42