Commit 2334fae
committed
feat: Add PrimeOrNot class with isPrime method for prime number check
WHAT the code does:
- Defines a `PrimeOrNot` class with a static method `isPrime(int x)`.
- `isPrime()` checks if a number is prime:
- Returns `false` for numbers ≤ 1.
- Loops from `2` to `x/2` checking divisibility.
- Returns `false` if any divisor is found, otherwise `true`.
- `main()` tests the method with numbers: 13, 91, 100, 2, and 1.
WHY this matters:
- Demonstrates prime number validation using basic loops and conditions.
- Reinforces modular arithmetic (`%`) and control flow.
- A classic programming exercise useful in interviews and algorithm practice.
HOW it works:
1. Input `x = 13` → loop finds no divisor → returns `true`.
2. Input `x = 91` → divisible by 7 → returns `false`.
3. Input `x = 100` → divisible by 2 → returns `false`.
4. Input `x = 2` → no divisors found → returns `true`.
5. Input `x = 1` → `<= 1` check → returns `false`.
Tips & gotchas:
- The loop `i <= x/2` works but is inefficient for large numbers → can be optimized to `i <= Math.sqrt(x)`.
- Handles negative numbers by treating them as not prime.
- For efficiency, you could check divisibility by 2 first, then loop odd numbers only.
- Returning early on divisor detection keeps it performant.
Use-cases:
- Educational example for prime checking.
- Useful in math-heavy applications or competitive programming.
- Can serve as a utility function in algorithms needing prime detection.
- Good base for extending to prime factorization.
Short key: algo-prime-check-basic.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 1ff2454 commit 2334fae
1 file changed
+27
-12
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | | - | |
3 | | - | |
| 2 | + | |
4 | 3 | | |
5 | 4 | | |
6 | 5 | | |
| 6 | + | |
| 7 | + | |
7 | 8 | | |
8 | 9 | | |
9 | | - | |
10 | | - | |
11 | | - | |
12 | | - | |
13 | | - | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
14 | 25 | | |
15 | | - | |
16 | | - | |
17 | | - | |
| 26 | + | |
| 27 | + | |
18 | 28 | | |
19 | 29 | | |
20 | | - | |
| 30 | + | |
21 | 31 | | |
22 | | - | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
0 commit comments