Home page

Friday, June 23, 2023

Print Prime number in JAVA

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In other words, a prime number is only divisible by 1 and itself.

Here's an example code in Java to print prime numbers up to a given limit:

public class PrimeNumbers {

    public static void main(String[] args) {

        int limit = 100; // Define the limit

        System.out.println("Prime numbers up to " + limit + ":");

        for (int number = 2; number <= limit; number++) {

            if (isPrime(number)) {

                System.out.print(number + " ");

            }

        }

    }

    // Check if a number is prime

    public static boolean isPrime(int number) {

        if (number <= 1) {

            return false;

        }

        for (int divisor = 2; divisor <= Math.sqrt(number); divisor++) {

            if (number % divisor == 0) {

                return false;

            }

        }

        return true;

    }

}

In this example, we set the limit variable to 100, which determines the range of numbers to check for primality.
We iterate over each number from 2 to the given limit.
Inside the loop, we call the isPrime() method to check if the current number is prime.
The isPrime() method checks if the number is less than or equal to 1 and returns false. Otherwise, it iterates from 2 up to the square root of the number to check for any divisors. If a divisor is found, the method returns false, indicating that the number is not prime. If no divisor is found, the method returns true, indicating that the number is prime.

Prime numbers are printed to the console.

Output:
Prime numbers up to 100:
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

The program prints all prime numbers from 2 to the specified limit (100 in this case). The isPrime() method is used to determine whether a number is prime or not by checking for divisors.

No comments:

Post a Comment