In: Computer Science
A prime number is an integer greater than 1 that is evenly divisible by only 1 and itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not. Create a PrimeNumber application that prompts the user for a number and then displays a message indicating whether the number is prime or not. Hint: The % operator can be used to determine if one number is evenly divisible by another. Java
Program:
import java.util.Scanner;
class primeno
{
public static void main(String ags[ ] )
{
int t;
boolean prime = true;
Scanner scan = new Scanner(system.in);
System.out.println("Enter a number");
int n= scan.nextInt();
scan.close();
for(int i=2; i <=n/2; i++)
{
t = n% i;
if(t==0)
{
prime = false;
break;
}
}
if(prime)
System.out.println(n + " is a prime number");
else
System.out.println(n + "is not a prime number");
}
}
Output 1:
Enter a number
7
7 is a prime number
Output 2:
Enter a number
8
8 is not a prime number
Working:
System.out.println ("enter a number"); -> In the output screen it will ask to enter a number
int n = scan.nextInt(); -> inputting a number n as datatype int
for( int i=2; i<=n/2;i++) -> initialize variable i by 2, condition is i<=n/2 and i++ is incrementing value of i by 1.
t = n%i; -> t is a variable which stores n% i, that is the remainder when n is divided by i
if (t==0)
{
prime= false
break;
} -> These statements first check whether the value of t = 0 . if t = 0 then prime will become false and comes out of condition.
if(prime)
System.out.println(n + " is a prime number");
else
System.out.println(n + "is not a prime number");
if prime is true then outpur the number is a prime number, otherwise output the number is not a prime number.