Google News
logo
Java Program to Print alternate Prime Numbers
The following example of Java program to print alternate prime numbers :
Program :
public class AlternatePrimeNumbers {
    public static void main(String[] args) {
        int n = 50; // change the value of n as per your requirement
        int count = 0;
        for (int i = 2; i <= n; i++) {
            boolean isPrime = true;
            for (int j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                count++;
                if (count % 2 == 1) {
                    System.out.print(i + " ");
                }
            }
        }
    }
}
Output :
2 5 11 17 23 31 41 47 
In this program, we start by initializing n to the maximum limit up to which we want to print the alternate prime numbers. We then initialize a variable count to keep track of the number of prime numbers found.

We then use a nested for loop to iterate through each number from 2 to n. The inner loop checks if the number is prime or not by dividing it with each number from 2 to its square root. If it is divisible by any number other than 1 and itself, then it is not a prime number.

If the number is prime, we increment the count variable and check if it is an odd or even number. If it is an odd number, we print it as an alternate prime number.

The output of the program for n = 50.