Skip to content

Instantly share code, notes, and snippets.

@Yonet
Created July 12, 2015 04:23
Show Gist options
  • Save Yonet/fd79a36c61fc27518cae to your computer and use it in GitHub Desktop.
Save Yonet/fd79a36c61fc27518cae to your computer and use it in GitHub Desktop.
Implementation of sqRoot
var sqRoot = function(n){
var upper = n;
var lower = 1;
var results = [1];
var search = function(){
var mid = Math.floor((upper + lower) /2);
var current = mid * mid;
if(upper === lower || mid === lower || mid === upper) {
results.sort(function(a, b) {return a - b;})
return results[results.length - 1];
} else if(current > n){
upper = mid;
return search();
} else {
if(current === n){
return mid;
} else {
results.push(mid);
upper = mid;
return search();
}
}
}
return search();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment