Skip to content

Commit 5ca41ba

Browse files
committed
feat: Add Questions class with prime check and Armstrong number listing
WHAT the code does: - Defines a `Questions` class for practicing number-related problems. - Prompts user for input and checks if the number is prime (`isPrime()`). - Prints all 3-digit Armstrong numbers (100–999) using `isArmstrong()`. WHY this matters: - Demonstrates **user input handling** with `Scanner`. - Shows **prime number check** using efficient loop up to √n. - Implements **Armstrong number check** for 3-digit numbers. - Useful educational example combining loops, conditionals, and modular arithmetic. HOW it works: 1. `isPrime(int n)`: - Returns false if `n <= 1`. - Loops from `2` to `√n`. - If divisor found, returns false; otherwise true. 2. `isArmstrong(int n)`: - Extracts digits of `n`. - Cubes each digit and sums them. - Returns true if sum equals original number. 3. `main()`: - Takes a number from user input and prints prime status. - Iterates from 100–999 and prints Armstrong numbers. Tips & gotchas: - `Scanner` should be closed after use to prevent resource leaks (`in.close()`). - Prime check optimized with `c * c <= n` → faster than looping to `n/2`. - `isArmstrong()` works only for 3-digit numbers; for n-digit, use `(int)Math.pow(rem, digits)`. - Input validation for non-integer entries not handled (will throw exception). Use-cases: - Competitive programming or coding interviews. - Teaching examples for **loops, conditionals, math operations**. - Can be extended to find primes/Armstrong numbers in any range. - Base utility for number theory problems. Short key: algo-prime-armstrong-check. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 04c8e35 commit 5ca41ba

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

Section10Methods/Methods 2.O/src/Questions.java

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@
33
public class Questions {
44
public static void main(String[] args) {
55
Scanner in = new Scanner(System.in);
6-
// int n = in.nextInt();
7-
// boolean ans = isPrime(n);
8-
// System.out.println(ans);
6+
System.out.println("Enter a number to check it is prime or not: ");
97

8+
int n = in.nextInt();
9+
boolean ans = isPrime(n);
10+
System.out.println(ans);
11+
12+
System.out.println("List of Armstrong numbers in range 100 to 1000 are: ");
1013
for (int i = 100; i < 1000; i++) {
1114
if (isArmstrong(i)) {
1215
System.out.print(i + " ");
@@ -24,10 +27,10 @@ static boolean isArmstrong(int n) {
2427
n = n / 10;
2528
sum = sum + rem*rem*rem;
2629
}
27-
2830
return sum == original;
2931
}
3032

33+
//declaring a method 'isPrime' and calling this method in main method.
3134
static boolean isPrime(int n) {
3235
if (n <= 1) {
3336
return false;

0 commit comments

Comments
 (0)