Computer Science, asked by Anonymous, 1 year ago

WAP in JAVA to check whether a number is prime or not .

Answers

Answered by Anonymous
13

CODE :


import java.util.*;

class prime_check

{

public void main()

{

Scanner sc=new Scanner(System.in);

System.out.println("Enter a number to check whether the number is prime or not");

int n=sc.nextInt();

int c=0;

for(int i=1;i<=n;i++)

{

if(n%i==0)

{

c++;

}

}

if(c==2)

{

System.out.println("Prime number");

}

else

{

System.out.println("Not a prime number");

}

}

}


WORKING :


Sample input : 87

Output:

Not a prime number


Sample input : 61

Output:

Prime number


LOGIC :


⇒ A prime number exactly has two factors - the number itself and one.

⇒ Thus I have checked with the for-loop the number of factors.


Hope it helps !

__________________________________________________________


Anonymous: thanks !
Anonymous: superb
Anonymous: tq
Answered by BrainlyPromoter
8
public class sum
{
public static void main(int n)
{
int c = 1;
int i = 0;
while(c < = n)
{
if(n ℅ c == 0 )
i++;
}
if(i == 2)
System.out.println("Yes, the given number is a prime number.");
else
System.out.println("No, the given number is not a prime number.");
}
}
Similar questions