Square Root Algorithm

Calculates the square root of a number with arbitrary precision using a similar technique to long division.

HTML

<div id='output' />

JavaScript

function square_root(n, precision)
{
    var pairs = (n + Array(precision*2+1).join("0")).match(/^.(?=((..)*)(..)$)|../g);
    
    for (var i=product=answer=remainder=0; i < pairs.length; i++)
    {
        remainder = (remainder - product) + pairs[i];
        for (var d=9; (product=((answer*20 + d) * d)) > remainder; d--){}
        answer = answer*10 + d;
    }  
    
    return answer / Math.pow(10,precision);
}

document.getElementById('output').innerHTML += square_root(55,4) + "<br />";
document.getElementById('output').innerHTML += square_root(54289,2) + "<br />";