Last active
February 3, 2024 07:36
-
-
Save mmloveaa/b684a229b37f98c370cd to your computer and use it in GitHub Desktop.
Find the next perfect square
This file contains 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
// 12/22/2015 | |
// You might know some pretty large perfect squares. But what about the NEXT one? | |
// Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. Recall that | |
an integral perfect square is an integer n such that sqrt(n) is also an integer. | |
// If the parameter is itself not a perfect square, than -1 should be returned. You may assume the parameter is positive. | |
// Examples: | |
// findNextSquare(121) --> returns 144 | |
// findNextSquare(625) --> returns 676 | |
// findNextSquare(114) --> returns -1 since 114 is not a perfect | |
// My Solution: | |
function findNextSquare(sq){ | |
var root1; | |
var nextroot; | |
if(Math.sqrt(sq)%1 ===0){ | |
root1=Math.sqrt(sq) | |
nextroot=root1+1 | |
}else{ | |
return -1; | |
} | |
return nextroot*nextroot; | |
} | |
findNextSquare(625) | |
// Or using ternary operator | |
function findNextSquare(sq){ | |
return Math.sqrt(sq)%1===0 ? Math.pow(Math.sqrt(sq)+1,2) : -1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
function findNextSquare(sq) {
// Check if the square root is an integer
const sqrt = Math.sqrt(sq);
if (Number.isInteger(sqrt)) {
// Find the next perfect square
const nextSquare = Math.pow(sqrt + 1, 2);
return nextSquare;
} else {
// If the parameter is not a perfect square, return -1
return -1;
}
}
// Example usage:
console.log(findNextSquare(9)); // Output: 16 (next perfect square after 9)
console.log(findNextSquare(25)); // Output: 36 (next perfect square after 25)
console.log(findNextSquare(10)); // Output: -1 (10 is not a perfect square)