Check Composite Number in PHP

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 2 Code Examples
Number theory

What you’ll learn

  • Composite vs prime definition.
  • n/2 and sqrt(n) trial-division checks.
  • Range scan and edge cases.

Overview

A number n>1 is composite if it has a factor between 1 and n.

Prerequisites

Loops and modulo checks.

  • for, if, %.
  • Basic integer comparisons.

What is a composite number?

Composite means n > 1 and n has more than two positive divisors.

Trial division bound

If n is composite, at least one factor is <= sqrt(n).

Intuition

12Composite
7Prime

Live preview

Live result
Press "Check" to classify.

Algorithm

Goal: decide if n is composite.

1

If n <= 1 return false.

2

Try divisors from 2 to sqrt(n).

3

If any divides n, return true; else false.

📜 Pseudocode

Pseudocode
if n <= 1: not composite
for i from 2 while i*i <= n:
  if n % i == 0: composite
not composite
1

Classic check up to n/2

php
<?php
function isCompositeHalf(int $n): bool
{
    if ($n <= 1) return false;
    for ($i = 2; $i <= intdiv($n, 2); $i++) {
        if ($n % $i === 0) return true;
    }
    return false;
}

$num = 12;
echo isCompositeHalf($num) ? "$num is a composite number." : "$num is not a composite number.";
?>
2

sqrt test and range scan

php
<?php
function isCompositeSqrt(int $n): bool
{
    if ($n <= 1) return false;
    for ($i = 2; $i <= intdiv($n, $i); $i++) {
        if ($n % $i === 0) return true;
    }
    return false;
}

echo "Composite numbers in the range 1 to 10 are:\n";
for ($i = 1; $i <= 10; $i++) {
    if (isCompositeSqrt($i)) echo $i . " ";
}
?>

Optimization

Use sqrt bound for faster checks.

Stop early as soon as one factor is found.

❓ FAQ

An integer n > 1 that has a divisor other than 1 and itself.
No. 1 is neither prime nor composite.
No, 2 is prime.
If n has a factor, at least one factor is <= sqrt(n), so checking further is unnecessary.
Single check with sqrt bound is O(sqrt(n)) time and O(1) space.

🔄 Input / output examples

nComposite?
12Yes
7No
1No (neither)

Edge cases and pitfalls

1

Neither prime nor composite

Donโ€™t mark 1 as composite.

2

Prime

Smallest prime; not composite.

⏱️ Time and space complexity

MethodTimeExtra space
up to n/2O(n)O(1)
up to sqrt(n)O(โˆšn)O(1)

Summary

  • Composite means n > 1 and not prime.
  • Trial division is standard method.
  • sqrt-bound version is faster.
Did you know?

The number 1 is neither prime nor composite; the smallest composite number is 4.

About the author

Mari Selvan M P
Mari Selvan M P ๐Ÿ”—

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful