- Because
- 4 × 4 = 16
- Verdict
- Perfect square.
Check Perfect Square in PHP
What you’ll learn
- What a perfect square is, with quick examples (1, 4, 9, 16…).
- How to test a value with a loop that only uses integer multiplication
i * i. - A second style using
sqrt()to list squares in a range. - A live preview and the usual edge cases (zero, negatives, big numbers).
Overview
Pick a whole number n. If there is some whole number k with k × k = n, then n is a perfect square. The programs below answer “Is this n a square?” and “Which squares sit between 1 and 50?”
Two programs
Example 1 walks i until i² passes n. Example 2 uses sqrt and prints every square in [1, 50].
Live preview
Try values like 15, 16, or 1 before you compile anything.
Interview-ready
Know both the integer loop and the library square-root trick, plus why floats need care at huge scales.
Prerequisites
Comfortable with tiny PHP programs and the idea of multiplying a number by itself.
- Basic PHP syntax,
forloops, and integer comparisons. - For Example 2: basic
sqrt()usage in PHP. - Basic squares:
1²=1,2²=4,3²=9,4²=16.
What is a perfect square?
A perfect square (in arithmetic) is any whole number you get by squaring another whole number: n = k² for some integer k. Negative k does not create new values because (−k)² is the same as k².
Non-examples help too: 2, 3, 5, 6, 7, 8 are not perfect squares. The next square after 9 is 16, so 10 through 15 sit between squares.
Quick examples
- Because
- 3² = 9 and 4² = 16; nothing in between.
- Verdict
- Not a perfect square.
- Because
- 1 × 1 = 1
- Verdict
- The smallest perfect square.
Live preview
Uses pure integer logic (no sqrt needed): find the smallest k with k² ≥ n, then check whether k² equals n.
Algorithm
Goal: decide whether a nonnegative integer n equals k² for some integer k.
Loop version
Try i = 1, 2, 3, … until i * i > n. If any step has i * i == n, return success. If you finish without a hit, n is not a square.
sqrt version
Let r be the integer part of sqrt(n). If r * r == n, then n is a perfect square. Be cautious with floating rounding when n is enormous.
📜 Pseudocode
function isPerfectSquareByLoop(n):
if n < 0:
return false
i ← 1
while i * i <= n:
if i * i = n:
return true
i ← i + 1
return falseInteger loop (no math library)
Try successive integers i. Stop when i² would pass n. This matches the classic interview answer and needs only stdio.h.
<?php
function isPerfectSquare(int $number): bool
{
if ($number < 0) {
return false;
}
for ($i = 1; $i * $i <= $number; $i++) {
if ($i * $i === $number) {
return true;
}
}
return $number === 0;
}
$testNumber = 16;
echo isPerfectSquare($testNumber)
? $testNumber . " is a perfect square.\n"
: $testNumber . " is not a perfect square.\n";
?>Explanation
When i reaches 4, we get 4 * 4 == 16, so the function returns 1 (true). If n were 15, the loop would pass 3 * 3 and then 4 * 4 without equality and return 0.
Using sqrt and listing a range
Here sqrt() gives a floating root; casting to int truncates toward zero. For each i from 1 to 50, we test whether i is a square. The loop includes 1, since 1 = 1².
<?php
function isPerfectSquare(int $num): bool
{
if ($num < 0) {
return false;
}
$root = (int)sqrt($num);
return $root * $root === $num;
}
echo "Perfect Squares in the Range 1 to 50:\n";
for ($i = 1; $i <= 50; $i++) {
if (isPerfectSquare($i)) {
echo $i . " ";
}
}
echo "\n";
?>Explanation
int root = sqrt(num); return root * root == num;Square-root shortcut. If truncating the square root and squaring again lands on num, then num is a perfect square.
for ($i = 1; $i <= 50; $i++) { if (isPerfectSquare($i)) echo $i . " "; }Outer loop. Tests every integer in the interval; only squares print. Change 50 to scan a different window.
Notes
Linking. PHP has sqrt() built in, so no separate math-linking flag is needed.
Floating limits. For very large n, sqrt in floating point can round wrong. Prefer the integer loop or wide integer libraries when n approaches 1012 and beyond.
Overflow. In the loop, i * i can overflow a 32-bit int if i grows too far; use a wider type or stop when i > n / i style checks are needed.
❓ FAQ
🔄 Input / output examples
Example 1 uses a fixed $testNumber. Replace it or read with trim(fgets(STDIN)) in PHP CLI for interactive runs.
| Value | Typical line (Example 1) |
|---|---|
| 16 | 16 is a perfect square. |
| 15 | 15 is not a perfect square. |
| 1 | 1 is a perfect square. |
| 0 | 0 is a perfect square. (if you extend the test for zero) |
Edge cases
These keep answers tidy in exams and code reviews.
n = 0Zero
0 = 0 × 0, so zero is a perfect square if your problem allows nonnegative integers. The loop for (i = 1; …) never runs for n = 0, so treat 0 as a special case if you need it.
No real integer square
Negative integers are not perfect squares of real integers. Return false immediately if the assignment restricts to nonnegative n.
sqrtRounding
Always compare by squaring the truncated root again, as in root * root == num. Never trust a bare floating equality against n without that check.
⏱️ Time and space complexity
| Approach | Time (single n) | Extra space |
|---|---|---|
Loop until i² > n | O(√n) | O(1) |
sqrt once | O(1) typical math cost | O(1) |
List squares in [1, U] | O(U) tests | O(1) |
Summary
- Idea:
nis a perfect square whenn = k²for some integerk. - Code: loop with
i * i, or takesqrtand verify by squaring the truncated root. - Watch: avoid overflow on
i * ifor huge values, and remember1is a square.
A perfect square is also a quadratic residue in everyday arithmetic: the count of objects you can arrange in a square grid with the same number of rows and columns. The gaps between consecutive squares 1, 4, 9, 16… grow by the odd numbers 3, 5, 7, 9…
9 people found this page helpful
