Practice › Basics
Perfect Square Check
Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
For each number, print YES if it is a perfect square (the square of an integer), otherwise NO.
Input
First line: q. Next q lines: one integer n each.
Output
q lines with YES or NO.
Constraints
- 1 ≤ q ≤ 10^4
- 0 ≤ n ≤ 10^18
Floating-point sqrt can be off by one for numbers this large. Take r = round(sqrt(n)) and check r − 1, r and r + 1 with exact integer multiplication — or binary search the integer square root.
Example 1
Input
4 16 15 0 1
Output
YES NO YES YES
Hints
- sqrt() works in floating point, which has only about 15–16 exact digits.
- For n near 10^18 the rounded square root can be off by one.
- Fix it with integer checks around the floating-point guess.
Approach
Let x = (long long) sqrtl(n). While x · x > n, decrease x; while (x + 1)² ≤ n, increase x. Now x is the exact integer square root and n is a perfect square exactly when x · x == n. In Python, math.isqrt is exact already. (x + 1)² stays below 2^63 because x ≤ 10^9.
Complexity: O(1) per query
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int q;
cin >> q;
while (q--) {
long long n;
cin >> n;
long long x = (long long) sqrtl((long double) n);
while (x * x > n) x--;
while ((x + 1) * (x + 1) <= n) x++;
cout << (x * x == n ? "YES" : "NO") << "\n";
}
return 0;
}Python solution
import sys
from math import isqrt
data = sys.stdin.read().split()
out = []
for t in data[1 : 1 + int(data[0])]:
n = int(t)
x = isqrt(n)
out.append("YES" if x * x == n else "NO")
print("\n".join(out))Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int q = Integer.parseInt(br.readLine().trim());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < q; i++) {
long n = Long.parseLong(br.readLine().trim());
long x = (long) Math.sqrt((double) n);
while (x * x > n) x--;
while ((x + 1) * (x + 1) <= n) x++;
sb.append(x * x == n ? "YES" : "NO").append('\n');
}
System.out.print(sb);
}
}