public class PrimeNumbers {
public static void main(String[] args) {
int num;
boolean isPrime;
System.out.println("Prime numbers between 1 and 100 are: ");
for (int i = 2; i <= 100; i++) {
isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(i + " ");
}
}
}
}
Prime numbers between 1 and 100 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) {
int num;
boolean isPrime;
Scanner input = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
num = input.nextInt();
input.close();
System.out.println("Prime numbers between 1 and " + num + " are: ");
for (int i = 2; i <= num; i++) {
isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(i + " ");
}
}
}
}
Enter a positive integer: 50
Prime numbers between 1 and 50 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
100
or n
, while the inner loop checks if the number is divisible by any number between 2 and half of the number. break
statement. If the number is not divisible by any number between 2 and half of the number, then it is a prime number and it is printed.