Computer Science, asked by shambhaviagrahari1, 6 months ago

java program for prime number ​

Answers

Answered by BrainlyProgrammer
4

Question:-

  • Java code to check if a number is a prime number or not

Answer:-

package Coder;

import java.util.*;

public class PrimeCheck {

public static void main(String[] args) {

Scanner sc=new Scanner (System.in);

System.out.println("Enter a number");

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");

}

}

Variable Description:-

  1. n:- to accept the number from the user as input
  2. i:- loop variable to run a loop from 1 to n
  3. c:- counter variable to count number of factors

Explaination:-

  • The program runs a loop from 1 to n (where n is the number entered by the user)
  • Each iteration, the program counts the factor of n
  • if the count of the factor is 2 then it's a prime no.
  • else it is not a prime number

•Output Attached.

Attachments:
Answered by Oreki
4

Code:

  import java.util.Scanner;  

  public class PrimeNumber {

       static boolean isPrime(int number) {

           int limit = (int) (Math.floor(Math.sqrt(number))) + 1;

           for (int i = 2; i < limit; i++)

               if (number % i == 0)

                   return false;

           return true;

       }

       public static void main(String[ ] args) {

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

           int number = new Scanner(System.in).nextInt( );

           System.out.println((isPrime(number) ? "Is" : "Not") + " Prime");

       }

  }

Sample I/O:

  Case 1:

       Enter a number - 12

       Not Prime

  Case 2:

       Enter a number - 13

       Is Prime

Similar questions