Perfect Square
Problem
A perfect square is the square of a whole number. Example: 16 = 4 x 4. Read an integer and print true if it is a perfect square, otherwise false. Negative numbers are not perfect squares.
Constraints
- -10^12 <= n <= 10^12
Examples
Input
16
Output
true
Input
15
Output
false
Solutions
The square root of a perfect square is a whole number. We round the root and square it again. Rounding protects us from tiny decimal errors such as 3.9999999.
/*
* Problem : Check if a number is a perfect square.
* Input : One integer.
* Output : true or false.
* Approach: Take the square root and test the root.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method receives a number and returns true if the number is a perfect square.
static boolean isPerfectSquare(long number) {
// Step 1: Negative numbers are never perfect squares.
if (number < 0) {
return false;
}
// Step 2: Take the square root and round it to the nearest whole number. Example: sqrt(16) = 4.
long root = Math.round(Math.sqrt(number));
// Step 3: Multiply the root by itself. The number is a perfect square only if we get the number back.
return root * root == number;
}
public static void main(String[] args) {
long number = new Scanner(System.in).nextLong();
System.out.println(isPerfectSquare(number));
}
}
Hints (2)
- What is the square root of 16? Is it a whole number?
- Why do we round before we multiply?