|
| 1 | +import java.util.Scanner; |
| 2 | + |
| 3 | +/** |
| 4 | + * Program Title: Prime Number Checker |
| 5 | + * Author: [Sreenivasulu-03] |
| 6 | + * Date: 2025-10-08 |
| 7 | + * |
| 8 | + * Description: This program checks whether a given number is a prime number or not. |
| 9 | + * A prime number is a number greater than 1 that has no positive divisors other than |
| 10 | + * 1 and itself. The program uses an efficient method by checking divisibility only up to √n. |
| 11 | + * |
| 12 | + * Time Complexity: O(√n) |
| 13 | + * Space Complexity: O(1) |
| 14 | + */ |
| 15 | + |
| 16 | +public class PrimeNumberCheck { |
| 17 | + |
| 18 | + /** |
| 19 | + * Checks if a number is prime. |
| 20 | + * @param n The number to check. |
| 21 | + * @return true if n is prime, false otherwise. |
| 22 | + */ |
| 23 | + public static boolean isPrime(int n) { |
| 24 | + if (n <= 1) return false; |
| 25 | + if (n == 2) return true; |
| 26 | + if (n % 2 == 0) return false; |
| 27 | + |
| 28 | + // Check divisibility from 3 to √n |
| 29 | + for (int i = 3; i * i <= n; i += 2) { |
| 30 | + if (n % i == 0) { |
| 31 | + return false; |
| 32 | + } |
| 33 | + } |
| 34 | + return true; |
| 35 | + } |
| 36 | + |
| 37 | + public static void main(String[] args) { |
| 38 | + try (Scanner sc = new Scanner(System.in)) { |
| 39 | + System.out.print("Enter a number: "); |
| 40 | + |
| 41 | + while (!sc.hasNextInt()) { |
| 42 | + System.out.print("Invalid input! Please enter a valid number: "); |
| 43 | + sc.next(); |
| 44 | + } |
| 45 | + |
| 46 | + int number = sc.nextInt(); |
| 47 | + |
| 48 | + if (isPrime(number)) { |
| 49 | + System.out.println(number + " is a prime number."); |
| 50 | + } else { |
| 51 | + System.out.println(number + " is not a prime number."); |
| 52 | + } |
| 53 | + } catch (Exception e) { |
| 54 | + System.err.println("An unexpected error occurred: " + e.getMessage()); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments