All challenges
Easy 0 solved 0% acceptance

Perfect Square Check

Decide whether an integer is the square of a whole number.

What you'll learn

  • Reuse an integer square root to test squares
  • Handle negative inputs
  • Avoid floating point comparisons

Problem

A perfect square is a number like 0, 1, 4, 9 or 16 that equals k × k for some integer k. Negative numbers are never perfect squares. Check with integer arithmetic so that very large inputs are handled exactly.

Implement perfect_square_check(n).

Input

n: The integer to test. It may be negative.

Output

Return true if n = k × k for some integer k, otherwise false.

Constraints

−10^18 ≤ n ≤ 10^18

Examples

Example 1
Input:
n = 49

Expected output:
expected = True
Input:
long long n = 49;

Expected output:
bool expected = true;
Input:
long n = 49;

Expected output:
bool expected = true;

Explanation

49 = 7 × 7, so the answer is true.

Example 2
Input:
n = 50

Expected output:
expected = False
Input:
long long n = 50;

Expected output:
bool expected = false;
Input:
long n = 50;

Expected output:
bool expected = false;

Explanation

7 × 7 = 49 and 8 × 8 = 64, and 50 falls between them, so the answer is false.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Find the integer square root r of n first.

Hint 2

n is a perfect square exactly when r × r equals n.

Hint 3

Return false right away for negative numbers.

Expected complexity

O(log n) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

The best passing solution of each coder. Faster, smaller and better-reviewed solutions rank higher.

No passing solutions yet. Solve it to take first place.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.