Write A Program In Java To Generate First N Prime Numbers

0

Write A Program In Java To Generate First N Prime Numbers

Write A Program In Java To Generate First N Prime Numbers

In this program, we will create a java program to generate prime numbers upto n term with the use of java conditional operator as well as loop statements.


Let's use the conditional operator and loop statements in a java program to generate first n prime numbers. 


Let's use the conditional operator and loop statements in a java program to generate first n prime numbers. 


Program
public class PrimeNumbers {
    public static void main(String[] args) {
        int n = 10; // number of primes to generate
        int count = 0;
        int num = 2;
        while (count < n) {
            boolean prime = true;
            for (int i = 2; i <= Math.sqrt(num); i++) {
                if (num % i == 0) {
                    prime = false;
                    break;
                }
            }
            if (prime) {
                count++;
                System.out.println(num);
            }
            num++;
        }
    }
}

Output
2 3 5 7 11 13 17 19 23 29


Explanation
This program uses a while loop to generate prime numbers until the desired count n is reached. Within the loop, it checks if the current number num is prime by checking if it is divisible by any number less than or equal to its square root. If it is not divisible, it is considered a prime number and is printed to the console. The num variable is then incremented and the loop continues until n prime numbers have been generated.

❤️ I Hope This Helps You Understand, Click Here To Do More Exercise In Java Programming.

Post a Comment

0Comments
Post a Comment (0)