Write a Program to Print Prime Numbers by Java

Profile Picture

saxenadivya859

Tuesday, 2024-08-13



Prime Number Program in Java | Edureka


Prime Number Printing in Java: A Short Guide


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.


Java Code to Print 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
    }
}


Explanation of the Code:


  1. Range Definition:
  • The program defines a range with start and end variables. In this example, the range is from 1 to 100.
  • You can change these values to print prime numbers in any desired range.
  1. Main Loop:
  • The for loop iterates through each number in the specified range.
  • For each number, the isPrime method is called to check if it is a prime number.
  1. Prime Checking (isPrime Method):
  • Initial Check: If the number is less than or equal to 1, it’s not prime.
  • Loop Through Possible Divisors: The loop checks divisibility starting from 2 up to the square root of the number. The square root is used because if n is divisible by a number greater than its square root, it must also be divisible by a number smaller than the square root.
  • Return Values: If any divisor is found, the function returns false, indicating the number is not prime. If no divisors are found, the function returns true.
  1. Output:
  • Prime numbers are printed in a single line, separated by spaces.


Sample Output:

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


Summary:

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.