1. The Logic Building (The Strategy)
The general rule for a Prime number is that it’s only divisible by 1 and itself. However, I realized a common confusion: 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).
2. Recipe Writing (The Algorithm)
I treated my 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.
3. The Ingredients (The Variables)
I gathered my "ingredients" for the Java code:
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")
}
Top comments (0)