Commit ac2fd3b
committed
feat: Add Questions2 class with prime and Armstrong number checks
WHAT the code does:
- Defines a `Questions2` class that checks whether a given number (`num = 153`) is:
1. **Prime** → has no divisors except 1 and itself.
2. **Armstrong** → sum of digits raised to the power of number of digits equals the number itself.
- Implements both checks without external methods, directly inside `main()`.
WHY this matters:
- Demonstrates fundamental **number theory problems** in Java.
- Reinforces logic building with loops, conditions, and arithmetic operations.
- Avoids using `Math.pow` by implementing power calculation manually, showing low-level control.
HOW it works:
1. **Prime check**:
- If `num <= 1` → not prime.
- Otherwise, loops from `2` to `num/2` checking divisibility.
- If divisible, sets `isPrime = false` and breaks loop.
- Prints `"Prime"` if no divisors found.
2. **Armstrong check**:
- Counts number of digits.
- For each digit, calculates `digit^digits` by repeated multiplication.
- Sums powered digits and compares with original number.
- Prints `"Armstrong"` if equal.
Tips & gotchas:
- Prime check could be optimized to loop only till `√num` instead of `num/2`.
- Armstrong logic works for any digit length, not just 3-digit numbers.
- If `num = 1`, code prints nothing (not prime, not Armstrong).
- Using manual power calculation avoids floating-point issues from `Math.pow`.
Use-cases:
- Classic **interview practice problems**.
- Educational demo for beginners learning loops and conditionals.
- Basis for building utility functions for prime/Armstrong checks.
- Can be extended to list all primes or Armstrong numbers in a range.
Short key: algo-prime-armstrong-inline.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 5ca41ba commit ac2fd3b
1 file changed
+47
-0
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
0 commit comments