Core Java Interview Questions in 2021

[]

A number that is divisible by 1 or itself is a Prime Number. 2, 3, 5, 7, 11, 13, 17 are examples of some Prime numbers.

Please Note: 0 and 1 are not a prime number.

Below is a simple Prime number Program in Java to check a number is Prime or Not.

import java.util.Scanner; public class PrimeExample { public static void main(String args[]) { int i, m = 0, flag = 0; Scanner scan = new Scanner(System.in); System.out.print(“Enter any number: “); // This method reads the number provided using keyboard int num = scan.nextInt(); // Closing Scanner after the use scan.close(); m = num / 2; if (num == 0 || num == 1) { System.out.println(num + ” is not prime number”); } else { for (i = 2; i <= m; i++) { if (num % i == 0) { System.out.println(num + " is not prime number"); flag = 1; break; } } if (flag == 0) { System.out.println(num + " is prime number"); } } //end of else } }
Source

Leave a comment

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