prime number
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:
- Input: Get the number.
- Loop: Check every number from 1 up to the input number.
- Check Remainder: Use the modulo operation (
%) to find where the remainder is 0. - Counter: Count how many times the remainder was 0.
- 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.forloop:- 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");
}