找出这个循环的大O.

时间:2015-01-21 12:03:31

标签: algorithm math big-o

所以我只是弄乱了jsfiddler并使用以下算法来计算sqrt而不使用Math.sqrt

var counter = 0;

function sqrt(x){
    var a, b;

    a = 1;
    b = x;
    while (Math.abs(a - b) > 0.1){
        a = (a + b) / 2;
        b = x / a;
        counter++;
    }

    return a;
}

var x = 64;
var result = sqrt(x);

alert('Result = ' + result + ' (number of iterations ' + counter + ')');

的jsfiddle:

http://jsfiddle.net/2wx99yxj/

您能否帮我确定上述算法的Big O复杂度?我试过并在O(1/2 * LogN)附近结束但是我不确定并且实际上需要一些帮助。感谢

解决

如上所述 - Babylonian Method的副本。我稍微更新了代码以反映error threshold,如下所示:

function sqrt(x){
    var a, b, error;

    error = 0.1;
    a = 1;
    b = x;
    while (Math.abs(a - b) > error){
        a = (a + b) / 2;
        b = x / a;
        counter++;
    }

    return a;
}

并且BigO结果是: O(log(log(x / error))

0 个答案:

没有答案