HomeJava

Write a program to print first n prime numbers in java

Write a program to print first n prime numbers in java
Like Tweet Pin it Share Share Email

In this program you will be making use of methods and creating an object of a class and calling the method. So you will see one method by name “isPrime” which takes an integer as an input and returns a boolean value, the returned boolean value evaluates to true if the given input number is a prime and evaluates to false if its not a prime number.

import java.lang.*;
public class PrimeNumbers
{
    public static void main(String rs[ ] )
    {
        // creating an object for a class
        PrimeNumbers pn = new PrimeNumbers();

        // calling method printPrimes of class PrimeNumbers, this method takes integer 
        // values as an input, the input says, how many number of prime numbers do you want to print.
        pn.printPrimes(20);
    }

    public void printPrimes(int noOfPrimes)
    {
         int primeCount = 0;
         
         // below for loop iterates until the value in primeCount is equal to noOfPrimes
         // which means that the loop is continued until the given number of prime numbers are identified.
         for(int i=1;primeCount<=noOfPrimes;i++)
         {
              // if current value of i is a prime then increment primeCount and print the value of the prime number.
              if(isPrime(i)) 
              {
                  primeCount++;
                  System.out.println("Prime Number:" + i);
              }
          
         }
    }
   // method to find if a given number is a prime or not.
   public boolean isPrime(int ipNum)
   {
       boolean flag = true;
       // as 1 and 2 are by default prime numbers, we can directly return they are prime numbers.
       if (ipNum == 2 || ipNum==1 ) return flag;
      // This loop is used to check if a given number is divisible by numbers other than 1 and itself
       for(int i=3;i

There may be more efficient ways of printing the first n prime numbers, we have tried to give the simplest way of doing the same, please feel free to share any queries in form of comments, we would be more than happy to help.

lambdatest

Comments (0)

Leave a Reply

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