Check Composite Number in JavaScript

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 2 Code examples + Try it
Number theory

What you’ll learn

  • The correct meaning of composite versus prime and why 1 is neither.
  • Trial division to n/2 (classic style) and to √n (interview-leaning optimization).
  • A range scan like 1–10, a browser live preview, and complexity / edge-case notes.

Overview

A positive integer n > 1 is composite if it has a divisor strictly between 1 and n. This page shows a straightforward loop (up to n/2) for one value, then a √n test reused to print composites in a small interval.

Two scripts

Single check with a familiar n/2 bound, then range output with a √n helper.

Live preview

Type an integer and see composite vs not composite (same trial rules as the samples).

Definitions fixed

Copy on some older pages confuses “more than two divisors” with “excluding 1 and itself”—here the wording matches standard number theory.

Prerequisites

Integer remainder (%), for loops, and inequalities.

  • console.log and Number.isInteger / safe integer checks for interactive demos.
  • Optional: Math.sqrt for limits; Example 2 avoids it with i <= n / i.

What is a composite number?

An integer n > 1 is composite if it is not prime—equivalently, there exists an integer d with 1 < d < n and n % d === 0. Equivalently, n has more than two positive divisors (counting 1 and n).

The integer 1 has only one positive divisor, so it is neither prime nor composite. The number 12 is composite because 2 and 3 (among others) divide it.

Prime exactly two divisors
Composite > two divisors
Unit n = 1

Trial division bound

If n > 1 is composite, write n = d · k with d the smallest divisor greater than 1. Then d is prime and d ≤ k, hence d2 ≤ n and d ≤ ⌊√n⌋.

n = 35

Smallest nontrivial factor is 5, and 5 ≤ √35 ≈ 5.92. No need to test 7 separately once 5 is found.

Intuition

12 Composite
Factor
2 · 6, 3 · 4
7 Prime
Divisors
1 and 7 only

Takeaway: one nontrivial factor is enough to prove composite; proving prime requires no factor up to √n.

Live preview

Enter an integer in the JavaScript safe range. Uses the same “factor in (1, n)” rule: n ≤ 1 is reported as neither composite nor prime in the usual sense.

Very large values may be slow in the browser; the samples focus on modest sizes in the safe integer range.

Live result
Press “Check” to classify the number.

Algorithm

Goal: decide whether n > 1 has any divisor d with 1 < d < n.

Reject small values

If n ≤ 1, return “not composite” (and not prime in the standard sense).

Trial division

For i from 2 up to ⌊n/2⌋ (loose bound) or while i · i ≤ n (tight bound), if n % i === 0, return composite.

Otherwise prime

If no divisor found, n is prime, hence not composite.

📜 Pseudocode

Pseudocode
function isComposite(n):
    if n ≤ 1:
        return false
    for i from 2 while i * i ≤ n:
        if n mod i = 0:
            return true
    return false
1

Classic trial up to n / 2

Same shape as the original walkthrough: scan i = 2 .. n/2. Correct for all n > 1, though not the tightest upper limit.

JavaScript
/** @param {number} number  integer > 1 typical */
function isComposite(number) {
  if (number <= 1) {
    return false;
  }

  for (let i = 2; i <= number / 2; i++) {
    if (number % i === 0) {
      return true;
    }
  }

  return false;
}

const num = 12;

if (isComposite(num)) {
  console.log(num + " is a composite number.");
} else {
  console.log(num + " is not a composite number.");
}
Try it Yourself

Explanation

Any nontrivial factor of n is at most n/2 when n ≥ 4, so the loop bound is safe. Smaller n are covered by the early loop range and the n ≤ 1 guard.

if (number <= 1)

Edge guard. 0 and 1 are not composite (and not prime).

2

√n test and composites from 1 to 10

Uses integer i <= n / i instead of Math.sqrt to avoid floating point. Prints the same line as the reference range demo: 4 6 8 9 10.

JavaScript
/** 1 = composite, 0 = prime or n <= 1 */
function isCompositeSqrt(n) {
  if (n <= 1) {
    return 0;
  }
  for (let i = 2; i <= n / i; i++) {
    if (n % i === 0) {
      return 1;
    }
  }
  return 0;
}

console.log("Composite numbers in the range 1 to 10 are: ");

let line = "";
for (let i = 1; i <= 10; i++) {
  if (isCompositeSqrt(i)) {
    line += i + " ";
  }
}
console.log(line.trim());
Try it Yourself

Explanation

The condition i <= n / i is equivalent to i · i ≤ n for positive integers without calling Math.sqrt.

return 0;

Prime branch. No divisor found in [2, √n], so n is prime and not composite.

Optimization

√ bound. Prefer i <= n / i over n/2 for large n.

Primes first. Testing only prime i (sieve or wheel) wins more but adds setup; rarely required for a one-off interview check.

Interview: define composite precisely, handle n ≤ 1, then cite the √ trial bound.

❓ FAQ

A composite number is an integer n strictly greater than 1 that is not prime: equivalently, n has a divisor d with 1 < d < n, or n has more than two positive divisors. Examples: 4, 6, 8, 9, 10.
No. By standard definition, 1 is a unit, not prime and not composite.
No. Two is prime; it has no divisor strictly between 1 and 2.
If n has a nontrivial divisor d, then n = d·k with d ≤ k, so d ≤ √n. Any composite n therefore has a divisor in [2, ⌊√n⌋]. Scanning up to n/2 is correct but looser; √n is the usual interview optimization.
Primality and compositeness are defined for integers greater than 1. Negative integers and 0 are classified separately; most simple demos assume a nonnegative or positive input.
Checking one n with trial up to √n is O(√n) time and O(1) extra space. Scanning every integer in [a,b] multiplies that cost.

🔄 Input / output examples

Change num in Example 1 or the loop bounds in Example 2 to experiment.

nComposite?Note
12YesDivisible by 2, 3, …
7NoPrime
1NoNeither prime nor composite
4YesSmallest composite

Edge cases and pitfalls

Loose wording about “excluding 1 and itself” often confuses beginners; the code paths below stay consistent with standard definitions.

n = 2

Smallest prime

The loop never finds a divisor; the function must return not composite. Do not label 2 as composite.

n = 1

Neither class

Printing “not composite” is true but does not mean “prime”—phrase the UI message carefully if you need both concepts.

Squares

i · i = n

Perfect squares such as 9 are composite; the √ loop catches factor 3 when 3 · 3 = 9.

Overflow

i * i <= n

Squaring i in a wide loop can exceed safe integers; using i <= n / i avoids i * i for n > 0 in typical Number paths.

⏱️ Time and space complexity

MethodTime (single n)Extra space
Trial to n/2O(n)O(1)
Trial to √n (i ≤ n/i)O(√n)O(1)
Range [a, b]O((b-a+1)√b) with √ test per valueO(1)

Constants differ between the n/2 and √ variants; asymptotically the √ bound dominates for large n.

Summary

  • Definition: composite means n > 1 and not prime; 1 is neither.
  • Code: trial division; tighten the loop with i <= n / i.
  • Watch-outs: wording in old tutorials, n = 2, and overflow on i * i for huge Number values.
Did you know?

The integer 1 is neither prime nor composite. The smallest composite is 4 (2 × 2). Every composite n has a prime divisor p with p ≤ √n, which is why trial division only needs to reach √n.

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