Tuesday, November 19, 2024

Java Program to Print Prime Numbers from 0 to 100


Understanding Prime Numbers

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In simpler terms, a prime number is only divisible by 1 and itself. For instance, 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29 are prime numbers.

Java Implementation

Here's a Java program to efficiently print all prime numbers between 0 and 100:

public class PrimeNumbers {

    public static void main(String[] args) {

        int number = 100;

        boolean isPrime;


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

            isPrime = true;

            for (int j = 2; j <= Math.sqrt(i); j++) {

                if (i % j == 0) {

                    isPrime = false;

                    break;

                }

            }

            if (isPrime) {

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

            }

        }

    }

}


Explanation:

 * Initialization: We initialize a variable number to 100, representing the upper limit. We also initialize a boolean variable isPrime to track whether a number is prime or not.

 * Outer Loop: The outer loop iterates from 2 to number. We start from 2 because 1 is not considered a prime number.

 * Inner Loop: The inner loop iterates from 2 to the square root of the current number i. This optimization is based on the fact that if a number i is not divisible by any number less than or equal to its square root, it's prime.

 * Prime Number Check: If i is divisible by any number j in the inner loop, isPrime is set to false, indicating that i is not prime.

 * Printing Prime Numbers: If the isPrime flag remains true after the inner loop, i is a prime number, and it's printed to the console.

Key Points:

 * Efficiency: The square root optimization significantly improves the efficiency of the algorithm, especially for larger numbers.

 * Clarity: The code is well-structured and easy to understand, with clear variable names and comments.

 * Correctness: The algorithm accurately identifies and prints prime numbers within the specified range.

 * Flexibility: The code can be easily modified to print prime numbers within a different range by changing the number variable.

By understanding the concept of prime numbers and applying this efficient Java implementation, you can effectively generate and print prime numbers as needed.



This Content Sponsored by Genreviews.Online


Genreviews.online is One of the Review Portal Site


Website Link: https://genreviews.online/


Sponsor Content: #genreviews.online, #genreviews, #productreviews, #bestreviews, #reviewportal


No comments:

Post a Comment