Created
July 12, 2015 04:23
-
-
Save Yonet/fd79a36c61fc27518cae to your computer and use it in GitHub Desktop.
Implementation of sqRoot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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