I created a function that will test to see if a given parameter is a square number.
Read about square numbers here: https://en.wikipedia.org/?title=Square_number
<
//1st
var isPerfectSquare = function(num) {
return Math.sqrt(num) % 1 === 0;
}
//2nd: loop through all the number from 1 to num
var isPerfectSquare = function(num) {
for(let i=1; i <= num ; i++){
let d = i * i;
if(d === num){
return true
}
}
}
// Optimize solution: Binary Search
var isPerfectSquare = function(num) {
if(num ==1)return true
let left = 2;
let right = Math.floor(num/2);
while(left <= right){
let middle = Math.floor((left + right)/2)
let sqr = middle * middle;
if(sqr == num){
return true
}else{
if(sqr > num){
right = middle -1
}else{
left = middle + 1
}
}
}
return false
};