Commit c5f9e54
committed
feat: Add FindPrimeNumber class with prime check using loop
WHAT the code does:
- Defines `FindPrimeNumber` class with static method `isPrime(int n)`.
- `isPrime()`:
- Loops from `2` to `n/2 - 1`.
- If any number divides `n`, returns `false`.
- Otherwise returns `true`.
- `main()`:
- Uses `Scanner` to read an integer from the user.
- Calls `isPrime()` and prints `true` if prime, `false` otherwise.
WHY this matters:
- Demonstrates a classic algorithm for **prime number detection**.
- Combines user input handling with logic-based computation.
- Introduces conditionals and loops for factor checking.
HOW it works:
1. User enters a number (e.g., `19`).
2. Loop checks divisibility from `2` up to `n/2`.
3. If divisor found, immediately returns `false`.
4. If no divisor found, returns `true`.
Tips & gotchas:
- Algorithm has inefficiency:
- Checking up to `n/2` is unnecessary; prime check only requires testing divisors up to `√n`.
- Edge cases not handled:
- `n <= 1` should return `false` (not prime).
- `n = 2` or `n = 3` should return `true`, but loop may fail correctly for `2`.
- Always close `Scanner` (`scanner.close()`).
- Output is just `true`/`false` → could be more user-friendly messages.
Use-cases:
- Educational demo for prime-checking logic.
- Good interview practice for optimizing loop bounds (`√n` check).
- Foundation for prime-related problems (prime factors, sieve of Eratosthenes).
- Useful for competitive programming warm-ups.
Short key: algo-prime-check-basic-loop.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 280e692 commit c5f9e54
1 file changed
+10
-11
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
| 3 | + | |
| 4 | + | |
4 | 5 | | |
5 | 6 | | |
6 | 7 | | |
7 | | - | |
8 | | - | |
| 8 | + | |
9 | 9 | | |
| 10 | + | |
10 | 11 | | |
11 | | - | |
| 12 | + | |
12 | 13 | | |
13 | | - | |
| 14 | + | |
14 | 15 | | |
15 | | - | |
16 | | - | |
| 16 | + | |
17 | 17 | | |
18 | | - | |
19 | | - | |
20 | | - | |
| 18 | + | |
21 | 19 | | |
22 | 20 | | |
| 21 | + | |
23 | 22 | | |
24 | 23 | | |
25 | 24 | | |
26 | | - | |
| 25 | + | |
0 commit comments