
saxenadivya859
Tuesday, 2024-08-13

Prime numbers are integers greater than 1 that have no divisors other than 1 and themselves. This means they cannot be evenly divided by any other number except 1 and the number itself. For instance, the numbers 2, 3, 5, 7, and 11 are prime, while numbers like 4, 6, and 9 are not because they have additional divisors.
In Java, you can write a simple program to print all prime numbers within a specified range. The program checks each number in the range to see if it's prime, then prints the prime numbers.
public class PrimeNumbers {
public static void main(String[] args) {
int start = 1; // Start of the range
int end = 100; // End of the range
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}
public static boolean isPrime(int num) {
if (num <= 1) return false; // Prime numbers are greater than 1
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false; // Not prime if divisible by any number other than 1 and itself
}
return true; // Number is prime
}
}
start and end variables. In this example, the range is from 1 to 100.for loop iterates through each number in the specified range.isPrime method is called to check if it is a prime number.n is divisible by a number greater than its square root, it must also be divisible by a number smaller than the square root.false, indicating the number is not prime. If no divisors are found, the function returns true.When you run the program with the range from 1 to 100, it produces the following output:
Copy code 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
This program provides a straightforward way to generate and print prime numbers in a given range using Java. The logic can be easily adapted for different ranges and is a good starting point for understanding how prime numbers work and how basic loops and conditionals operate in Java.