prime number

Published: (January 3, 2026 at 07:46 AM EST)
1 min read
Source: Dev.to

Source: Dev.to

The Logic Building (The Strategy)

The general rule for a prime number is that it’s only divisible by 1 and itself. However, a common confusion is that composite numbers (like 4) are also divisible by 1 and themselves.

  • Prime Number (e.g., 5): When divided by every number from 1 to itself, it produces a remainder of zero exactly two times ( 1 and 5 ).
  • Composite Number (e.g., 4): It produces a remainder of zero more than two times ( 1, 2, and 4 ).

Recipe Writing (The Algorithm)

Treat the code like a recipe:

  1. Input: Get the number.
  2. Loop: Check every number from 1 up to the input number.
  3. Check Remainder: Use the modulo operation (%) to find where the remainder is 0.
  4. Counter: Count how many times the remainder was 0.
  5. Final Result: If the count is exactly 2, it’s prime; otherwise, it’s composite.

The Ingredients (The Variables)

  • input: The number to check.
  • count: To track the number of divisors.
  • for loop:
    • Start: 1 (initialization)
    • End: Input (condition)
    • Next step: +1 (increment)
  • if‑else: To handle the logic.

Program (JavaScript)

var a = 24;
var c = 0;

for (i = 1; i <= a; i++) {
    if (a % i == 0) {
        c++;
    }
}

if (c == 2) {
    console.log("Prime");
} else {
    console.log("Not Prime");
}
Back to Blog

Related posts

Read more »

1390. Four Divisors

Problem Statement Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such in...