/ Assignment / assignment_22.java
assignment_22.java
1 /* 2 * Write program to find Kth prime number 3 */ 4 import java.util.Scanner; 5 import java.util.ArrayList; 6 7 public class assignment_22 { 8 public static int kth_prime_no(int K) { 9 int N = 1000; // Upper bound for prime search 10 boolean[] array = new boolean[N + 1]; // Corrected boolean array declaration 11 12 // Initialize the array 13 for (int i = 0; i <= N; i++) { 14 if (i == 0 || i == 1) { 15 array[i] = false; // 0 and 1 are not prime 16 } else { 17 array[i] = true; // Assume all others are prime initially 18 } 19 } 20 21 // Sieve of Eratosthenes to mark non-prime numbers 22 for (int j = 2; j <= Math.sqrt(N); j++) { 23 if (array[j]) { // If j is prime 24 for (int k = j * j; k <= N; k += j) { // Mark multiples as non-prime 25 array[k] = false; 26 } 27 } 28 } 29 30 // Collect prime numbers in a list 31 ArrayList<Integer> primes = new ArrayList<>(); 32 for (int i = 2; i <= N; i++) { 33 if (array[i]) { 34 primes.add(i); 35 } 36 } 37 38 // Return the K-th prime number 39 if (K - 1 < primes.size()) { 40 return primes.get(K - 1); // ArrayList uses .get(index) 41 } else { 42 return -1; // Return -1 if K is out of bounds 43 } 44 } 45 46 public static void main(String[] args) { 47 Scanner sc = new Scanner(System.in); 48 System.out.print("Enter the value of K: "); 49 int k = sc.nextInt(); 50 sc.close(); 51 52 int result = kth_prime_no(k); 53 if (result != -1) { 54 System.out.println("The " + k + "th prime number is: " + result); 55 } else { 56 System.out.println("Invalid input: K is too large."); 57 } 58 } 59 }