const input_number = document.querySelector("#input-number");
const btn_submit = document.querySelector("#btn-submit");
const output = document.querySelector("#output");

/**
 * Based on Newton`s algorithm:
 * https://math.mit.edu/~stevenj/18.335/newton-sqrt.pdf
 * https://www.school-for-champions.com/algebra/square_root_approx.htm
*/
function my_sqrt(number)
{
    if (number == 0 || number == 1)
    {
        return number;
    }

    let dividend = number;
    let ret = number;
    let last;

    do {
        last = ret;
        ret = (ret + dividend / ret) * 0.5;
    } while (Math.abs(ret - last) > 1e-9); // where 1e-9 - precision

    return ret;
}

btn_submit.addEventListener("click", (event) => {
    const number = input_number.value;
    const result = my_sqrt(number);
    output.textContent = `Result: ${result}`;
});
