The program takes input from the use and finds whether the given input is a prime number or not. A prime number is a number which has exactly two factors 1 and the number itself. For example, 5,7,11….
Program:
import java.util.Scanner; public class PrimeOrNot{ public static void main(String[] args) { int num,i,flag=0; System.out.print("Please enter a number = "); Scanner ed = new Scanner(System.in); num= ed.nextInt(); for(i=2;i<= num/2;i++) { if(num%i==0) { flag=1; break; } } if(num==2) System.out.println(num+" is an even prime number . "); else if(num==1) System.out.println(num+" isn't a prime or composite number . "); else if(flag==1) System.out.println(num+" isn't prime number . "); else System.out.println(num+" is a prime number . "); } }
public static void main(String[] args) { int num, i=2, flag = 0; System.out.print("Please enter a number = "); Scanner ed = new Scanner(System.in); num = ed.nextInt(); while (i <= num / 2) { if (num % i == 0) { flag = 1; break; } i++; } if (num == 2) System.out.println(num + " is an even prime number . "); else if (num == 1) System.out.println(num + " isn't a prime or composite number . "); else if (flag == 1) System.out.println(num + " isn't prime number . "); else System.out.println(num + " is a prime number . "); }
Output:
Please enter a number = 131 131 is a prime number
This post was last modified on December 27, 2020