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 + " ");
}
}
}
}
}
2 5 11 17 23 31 41 47
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.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.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.n = 50
.