- Check idea
- No
ifrom2to√17divides17.
Check Prime Number in JavaScript
What you’ll learn
- A clear idea of prime versus composite, and why 1 is a special case.
- How trial division works: try possible factors and stop early when you find one.
- Two complete JavaScript programs: check one number (with a tight loop bound) and print primes between 1 and 20, plus a browser live preview.
Overview
You will answer one question: “Is this whole number n prime?” A prime has no divisor strictly between 1 and n. The code tries candidate divisors; if none work, n is prime. A second program reuses the same test to print small primes in a range.
Two programs
Example 1 checks a single value (here 17). Example 2 lists primes from 1 to 20.
Live preview
Type a number and see prime or not prime, with the first factor shown when it is not prime.
Interview-ready detail
Edge cases (n ≤ 1, 2), the square-root loop bound, and complexity in one place.
Prerequisites
You should be fine if you have written small JavaScript programs with loops and console.log.
- Function declarations,
forloops, andconsole.log. forloops and the remainder operator%(read “n modulo i equals zero” as “i divides n evenly”).
What is a prime number?
A prime number is an integer greater than 1 whose only positive divisors are 1 and itself. If you can find any other integer between 1 and that number that divides it evenly, the number is not prime (it is composite).
Think of primes as building blocks: 12 = 2 × 2 × 3 uses primes 2 and 3. The number 17 cannot be split that way using smaller whole factors, so 17 is prime.
Why the square-root bound works
Suppose n > 1 is not prime. Then n = a × b where both a and b are integers greater than 1. One of them cannot be larger than √n without the product exceeding n. So some divisor (other than 1) appears in the range 2 through ⌊√n⌋.
n = 15We find 3 × 5 = 15. The factor 3 is less than or equal to √15 ≈ 3.87. The loop reaches 3 and proves 15 is not prime.
Quick examples
- Factor
2 × 9,3 × 6, …
Takeaway: one successful division is enough to say “not prime”; proving prime means no divisor up to √n.
Live preview
This uses the same trial idea as the C samples: try i while i · i ≤ n. For very large n the browser may slow down; this demo caps input size so the tab stays smooth.
- Enter a whole number (try 17, 1, or 18).
- Press Run check or Enter.
- Read whether it is prime; if not, you will see a small factor that proves it.
Algorithm
Goal: return “prime” if n has no divisor strictly between 1 and n; otherwise return “not prime”.
Handle small values
If n ≤ 1, it is not prime by definition. Return false (or print a clear message).
Try candidate divisors
Let i run from 2 upward while i · i ≤ n (same as i ≤ n / i for positive n). If n % i == 0, you found a nontrivial factor—stop: not prime.
Finish
If the loop completes with no hit, n is prime.
List primes in [start, end]
For each integer k in the interval, call the same test. When the test says prime, print k. Values ≤ 1 are skipped.
📜 Pseudocode
function isPrime(n):
if n < 2:
return false
for i from 2 while i * i ≤ n:
if n mod i = 0:
return false
return trueCheck a single number (square-root loop)
Classic interview shape: reject n ≤ 1, then trial division with i ≤ n / i so we never multiply i by itself in a way that risks overflow on large int values.
function isPrime(n) {
if (n <= 1) {
return false;
}
for (let i = 2; i <= n / i; i++) {
if (n % i === 0) {
return false;
}
}
return true;
}
const testNumber = 17;
if (isPrime(testNumber)) {
console.log(testNumber + " is a prime number.");
} else {
console.log(testNumber + " is not a prime number.");
}Explanation
Walk through the function the way you would in an oral exam: guard, loop, early exit, default to prime.
if (n <= 1) return 0;Definition first. Zero, one, and negatives are not prime in the usual textbook sense.
for (int i = 2; i <= n / i; ++i)Tight bound. This is equivalent to i * i <= n but avoids computing i * i for big integers.
if (n % i == 0) return 0;Found a factor. Then n has more than two divisors, so it cannot be prime.
return 1;No factor up to √n. Therefore n is prime.
Prime numbers between 1 and 20
Same helper as many textbooks: loop i from 2 while i * i ≤ num. The outer loop prints every prime in the closed range [1, 20] (so 1 is skipped automatically).
function isPrime(num) {
if (num <= 1) {
return false;
}
for (let i = 2; i * i <= num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
function listPrimesInRange(start, end) {
const values = [];
for (let i = start; i <= end; i++) {
if (isPrime(i)) {
values.push(String(i));
}
}
console.log("Prime numbers in the range " + start + " to " + end + ":");
console.log(values.join(" "));
}
const start = 1;
const end = 20;
listPrimesInRange(start, end);Explanation
list_primes_in_range is only a thin wrapper: it calls is_prime for each candidate and prints hits.
for (int i = start; i <= end; ++i)Outer scan. Change start and end to match your assignment; keep them sensible so the program finishes quickly.
if (isPrime(i)) values.push(String(i));Reuse the test. You do not rewrite the math—one function stays the single source of truth.
Optimization and style notes
Even check. After testing 2, you can step i by 2 to skip even candidates (handle 2 before the loop). Helpful when n is large and you want a constant-factor speedup.
Precomputed tables. If you need many primes up to a limit N, a sieve of Eratosthenes beats repeated trial division; this page sticks to the simple method for clarity.
Interview: state the definition, guard n < 2, then give trial division to √n with O(√n) time.
❓ FAQ
🔄 Input / output examples
For Example 1, change testNumber in the script. For interactive code, read from prompt (browser) or readline (Node.js).
Input n | Typical line printed |
|---|---|
17 | 17 is a prime number. |
18 | 18 is not a prime number. |
2 | 2 is a prime number. |
1 | 1 is not a prime number. |
For Example 2 with start = 1 and end = 20:
Prime numbers in the range 1 to 20:
2 3 5 7 11 13 17 19Edge cases and pitfalls
Most bugs come from the boundaries 0, 1, and 2, or from using a loop that never runs when it should.
Smallest prime
The inner loop should not reject 2. With i starting at 2 and condition i ≤ n / i, the loop body does not run for n = 2, and the function correctly returns prime.
Not prime
Returning “not prime” is correct; do not call 1 prime in your print message.
Perfect squares
9 is not prime because 3 × 3 = 9. The trial loop catches i = 3.
i * i in JavaScript
For very large values, prefer i <= n / i or cap inputs in UI previews so the check remains responsive.
⏱️ Time and space complexity
| Method | Time (single n) | Extra space |
|---|---|---|
Trial to n / 2 | O(n) | O(1) |
Trial to √n (i ≤ n/i) | O(√n) | O(1) |
All k in [a, b] with √ test each | roughly O((b-a)√b) | O(1) |
Only a handful of integer variables are used, so extra memory stays constant aside from the normal call stack.
Summary
- Definition: primes are integers
n > 1with no divisor strictly between1andn. - Code: trial division; stop at
√nand return early when a factor appears. - Watch-outs: treat
n ≤ 1first, remember2is prime, and avoidi * ioverflow on hugeintvalues.
The only even prime is 2. Every integer greater than 1 is either prime or composite—except 1, which is neither. There are infinitely many primes (a classic proof attributed to Euclid).
9 people found this page helpful
