Different Methods to find Prime Number in Java

Java 8Object Oriented ProgrammingProgramming

A prime number is a number that is only divisible by one or itself. Some of the prime numbers are 2, 3, 5, 7, 11, 13 etc.

Some of the different methods to find a prime number in Java are given as follows −

Method 1 - Find if a number is prime without using a function

A program that finds if the given number is prime without using a function is given as follow −

Example

 Live Demo

public class Example {
   public static void main(String args[]) {
      int num = 11, flag=0;
      if(num == 0||num == 1) {
         System.out.println( num + " is not a prime number");
      } else {
         for(int i = 2; i <= num/2; i++) {
            if(num % i == 0) {
               System.out.println( num + " is not prime number");
               flag = 1;
               break;
            }
         }
         if(flag == 0) {
            System.out.println( num + " is a prime number");
         }
      }
   }
}

Output

11 is a prime number

Method 2 - Find if a number is prime using a function

A program that finds if the given number is prime using a function is given as follow −

Example

 Live Demo

public class Example {
   static int PrimeOrNot(int num) {
      int flag = 0;
      if(num == 0||num == 1) {
         flag = 1;
      } else {
         for(int i = 2; i <= num/2; i++) {
            if(num % i == 0) {
               flag = 1;
               break;
            }
         }
      }
      return flag;
   }
   public static void main(String args[]) {
      int flag, num = 11;
      flag = PrimeOrNot(num);
      if(flag == 0) {
         System.out.println( num + " is a prime number");
      } else {
         System.out.println( num + " is not a prime number");
      }
   }
}

Output

11 is a prime number
raja
Published on 10-Dec-2018 07:14:39
Advertisements