Print First 10 Prime Numbers in Java

Print First 10 Prime Numbers in Java | Prime numbers are natural numbers that are divisible by only 1 and the number itself. In other words, prime numbers are positive integers greater than 1 with exactly two factors, 1 and the number itself. Also see:- Prime Number Program in Java

For example– 2 is a prime number because it has only two factors 1 and 2.

Similarly,
4 is not a prime number because it has more than 2 factors that are 1, 2, and 4.

Note:- All negative numbers, 0 and 1 are not the prime numbers.

In this program, we will use the While Loop to print the first 10 prime numbers.

Program description:- Write a program to print the first 10 prime numbers in java

public class PrimeNumber {

  public static boolean isPrime(int number) {

    /* Negative numbers, 0 and 1 
    * are not a prime number
    * 
    * Even numbers (except 2) are
    * also not a prime number
    */
    if(number == 2) return true;
    else if(number<=1 || number%2==0)
         return false;

    // logic for remaining numbers
    for(int i=3; i<=Math.sqrt(number); i++){
         if(number%i == 0) return false;
    }

    return true;
  }

  public static void main(String[] args) {

    System.out.println(
      "The First 10 prime numbers in Java are::");

    // variables
    int i=1, count=0;

    // loop to repeat the process
    while(count<10) {
       if(isPrime(i)) {
          System.out.print( i + " ");
          count++;
       }
       i++;
    }
  }
}

Output:-

The first 10 prime numbers in Java are::
2 3 5 7 11 13 17 19 23 29

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *