Java program to print a prime number

Java Programming Java8Object Oriented Programming

Any whole number which is greater than 1 and has only two factors that is 1 and the number itself, is called a prime number. Other than these two number it has no positive divisor. For example

7 = 1 × 7

Few prime number are − 1, 2, 3, 5 , 7, 11 etc.

Algorithm

1. Take integer variable A
2. Divide the variable A with (A-1 to 2)
3. If A is divisible by any value (A-1 to 2) it is not prime
4. Else it is prime

Example

import java.util.Scanner;
public class PrimeNumber {
   public static void main(String args[]){
      int loop, number;
      int prime = 1;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a number ::");
      number = sc.nextInt();
     
      for(loop = 2; loop < number; loop++) {
         if((number % loop) == 0) {
            prime = 0;
         }
      }
      if (prime == 1)
         System.out.println(number+" is a prime number");
      else
         System.out.println(number+" is not a prime number");
   }
}

Output

Enter a number ::
2
2 is a prime number
raja
Published on 25-Apr-2018 10:21:39
Advertisements