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 »

Coding Challenge Practice - Question 97

Problem Description The task is to find the k‑th largest element in an unsorted array that may contain duplicates. The k‑th largest element is the element that...

[BOJ/C++] 단계별로 풀어보기 - 브루트 포스

2026.01.08일차 입니다. 브루트 포스 풀어보았습니다. 브루트 포스Brute Force란 무차별 대입이라고도 부르며 모든 경우의 수를 대입하여 답을 찾는 방법입니다. 2798번 블랙잭 문제 링크 NC3 문제이므로 세 개의 반복문을 통해 구현해야 합니다. cpp include usi...