Computer Science, asked by dds6, 11 months ago

Java program to find the the number is prime or not by import class method

Answers

Answered by Somebodyme
1
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
boolean b = true;
if(x<=0){
System.out.println("This is not a prime number!");
}
else{
for(int i=2; i<=Math.sqrt(x); i++){
if(x%i==0){
b=false;
break;
}

}
if(b==true){
System.out.println("This is a prime number!");
} else{
System.out.println("It's not a prime number!");
}}
}
}
Answered by QGP
4
Here's the JAVA Code for a program. Paste it into an IDE to properly see the comments.


import java.util.Scanner;           //Importing Scanner Objectpublic class Prime                  //Creating a Class
{
    public static void main(String[] args)      //The main() function
    {
        Scanner sc = new Scanner(System.in);        //Creating a Scanner Object
       
        System.out.print("Enter a number: ");       //Asking for User Input
        int n = sc.nextInt();                       //Scanning User Input
       
        System.out.println();
       
        if(isPrime(n))              //This calls the method isPrime(int n), and if true, executes the code
        {
            System.out.println(n+" is a Prime Number");
        }
        else
        {
            System.out.println(n+" is a Composite Number");
        }
       
    }
    static boolean isPrime(int n)       //This method checks whether input number n is a Prime or not
    {
        boolean isPrime = true;         //By default, the boolean variable isPrime is set as true
        for(int i=2;i<=(int)Math.sqrt(n);i++)
        {
            if(n%i==0)
            {
                isPrime=false;          //If n is divisible by some number, isPrime is set as false, and loop is broken
                break;
            }
        }
        return isPrime;                 //The corresponding value, either true or false, is returned
    }
}

Similar questions