Computer Science, asked by Anonymous, 4 months ago

Write a program in Java to accept a number and check whether the number is prime or not.​

Answers

Answered by saanvigrover2007
4

public class PrimeExample{

public static void main(String args[]){

int i,m=0,flag=0;

int n=3;//it is the number to be checked

m=n/2;

if(n==0||n==1){

System.out.println(n+" is not prime number");

}else{

for(i=2;i<=m;i++){

if(n%i==0){

System.out.println(n+" is not prime number");

flag=1;

break;

}

}

if(flag==0) { System.out.println(n+" is prime number"); }

}//end of else

}

}

Answered by anindyaadhikari13
9

Required Answer:-

Question:

  • Write a program in Java to accept a number and check whether the number is prime or not.

Solution:

Here is the program.

import java.util.*;

public class Prime {

 public static void main(String[] args) {

    Scanner sc=new Scanner(System.in);

    System.out.print("Enter a number: ");

    int n=sc.nextInt(), c=0;

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

       if(n%i==0)

         c++;

    }

    if(c==2)

      System.out.print("Number is Prime.");

    else

      System.out.print("Number is not Prime.");

    sc.close();

 }

}

Explanation:

  • A number is said to be prime if it is only divisible by 1 and itself. Therefore, total number of factors of a prime number is 2 (1 and itself). So, we will count the factors of the number. If the total number of factors of the number is 2, then it is a prime number else not.

Refer to the attachment ☑.

Attachments:
Similar questions