JSFiddle - React, Tailwind, and code Playground

by andyshora

JavaScript

// function to manually calculate square root in javascript
// returns false on error or no integer square root
function calcSquareRoot(x){
    
    if (typeof x !== 'number') return false;
    if (x===1) return x; // test for 1, quickest = doesnt mess with logic below
    if (i<0) return false;
    
    for(var i=2; i<=(x/2); i++){
        if (i*i === x) return i;
    }
    
    return false;
}

document.write(calcSquareRoot(225));
document.write('<br />');
document.write(calcSquareRoot(226));
document.write('<br />');
document.write(calcSquareRoot(-1));
document.write('<br />');
document.write(calcSquareRoot(1));
document.write('<br />');
document.write(calcSquareRoot('2'));
document.write('<br />');
document.write(calcSquareRoot(4));