×

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can be used to divide prime integers. Prime numbers include 2, 3, 5, 7, 11, 13, and 17.

One and zero are not prime numbers. The number two is the only even prime number, therefore all other even numbers can be divided by it.

Java Prime Number Search Technique

  • Consider entering a number.
  • Since two is the lowest prime number, see if the number has a divisor in the range [two, number/2].
  • No integer may be entirely split by a factor greater than its own half. The number itself (number/2) must be looped through two times.
  • If a divisor can be identified, the provided number is not prime; else, it is.

Example

Let's say that 121 was entered as the value. It is put into the num integer variable.

 Since a number is being divided by both itself and by the number 1, num is now divided by other numbers ranging from 2 to 8 (% returns residual). The message "Number is not prime" is displayed on the screen if the integer is divided by any number between 2 and 8, as its remainder will be 0. Since 121 cannot be divided by 2, but can undoubtedly be divided by 3, which gives a remainder of 0, it cannot be a prime number.

Prime Number Program Algorithm

Step 1: Read the number.

Step 2: x = 1, y = 0

Step 3: Continue until step 5 while ensuring that (x =  num)

Step 4: Set y = y + 1 if (num mod x) equals 0.

Step 5: x  =  x + 1

Step 6: Print "num is prime" if y equals 2.

            Print "num is not prime" if not.

Step 7: Exit

Example 1:

import java.util.Scanner; 
 public class PrimeNumber
 { 
     public static void main(String args[]) 
              { 
                   int n,x,y; 
                   Scanner sc=new Scanner(System.in); 
System.out.println("Enter any Number: "); 
                   n =sc.nextInt(); 
                   x=1; 
                   y=0; 
while(x<= n) 
                       { 
                           if((n%x)==0) 
                              y=y+1; 
                              x++; 
                       } 
                        if(x==2) 
System.out.println(n +" is a prime number"); 
                        else 
System.out.println(n +" is not a prime number"); 
              } 
 }

Output

Enter any Number: 3
3 is not a prime number

Example 2:

Using the is Prime() function, which accepts a number as input and gives true if a number is a prime number and false otherwise, is a viable option.

import java.util.Scanner;
class PrimeNUmber {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
System.out.println("Enter any number : ");
        int number= sc.nextInt();
        if(isPrime(number)) {
System.out.println(number + " is a prime number");
        }
else{
System.out.println(number + " is not a  prime number");
        }
    }
static  booleanisPrime(int n)
    {
if(n <=1)
        {
            return false;
        }
for(int i=2;i<=n/2;i++)
       {
           if((n%i)==0)
return  false;
       }
       return true;
    }
}

Output

Enter any Number: 2
2 is a prime number

Example 3:

import java.util.Scanner;  
import java.util.Scanner;  
public class PrimeNumber {  
   public static void main(String[] args) {  
       Scanner sc = new Scanner(System.in);  
System.out.print("Enter any number : ");  
       int n = s.nextInt();  
       if (isPrime(n)) {  
System.out.println(n + " is a prime number");  
       } else {  
System.out.println(n + " is not a prime number");  
       }  
   }  
   public static booleanisPrime(int n) {  
       if (n <= 1) {  
           return false;  
       }  
       for (int i = 2; i<Math.sqrt(n); i++) {  
           if (n % i == 0) {  
               return false;  
           }  
       }  
       return true;  
   }  
}   

Output

Enter any Number: 11
11 is a prime number

Example 4:

import java.util.Scanner;  
public class PrimeNumber {  
   public static void main(String[] args) {  
       Scanner sc = new Scanner(System.in);  
System.out.print("Enter the 1 stnumber : ");  
       int start = sc.nextInt();  
System.out.print("Enter the 2 ndnumber : ");  
       int end = sc.nextInt();  
System.out.println("List of prime numbers between " + start + " and " + end);  
       for (int i = start; i<= end; i++) {  
           if (isPrime(i)) {  
System.out.println(i);  
           }  
       }  
   }  
   public static booleanisPrime(int n) {  
       if (n <= 1) {  
           return false;  
       }  
       for (int i = 2; i<= Math.sqrt(n); i++) {  
           if (n % i == 0) {  
               return false;  
           }  
       }  
       return true;  
   }  
}  

Output

Enter the 1 st number: 2
Enter the 2 nd number: 5
List of prime numbers between 2 and 5
2
3
5

Related Topics

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

Generics in Java

Generics in Java Parameterizedtypes mean generic. Generics allow types (Character, Integer, String, …, etc., as well as user-defined types) to act as parameters to interfaces, classes, and methods. Generics in Java...

9 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

Sort Elements by Frequency in Java

To sort the elements in Java by using frequency, we need an input array. We should create a function that sorts the elements in an array by using their frequencies...

3 minutes read.

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

Java Boolean logicalXor() Method

The logicalXor() method of Java Boolean class returns the result of implementing logical XOR operation on the specified Boolean operands. Syntax: public static boolean logicalXor (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

Java Math subtractExact() Method

The subtractExact() method of Java Math class returns mathematical difference of the specified two arguments, throwing an exception if the result overflows int or long. Syntax: public static int subtractExact (int x,...

1 minute read.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.

Find Unique Elements in Array Java

An array in Java is a grouping of objects that share the same type of data. We are free to enter identical or repeating elements into an array. Therefore, we...

6 minutes read.

Nth node from the end of the Linked list in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

6 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

How to calculate time difference in Java

In this tutorial, we learned about how to calculate time differences in java language and which methods use to find the difference and its example. Prerequisite To understand this example, you need...

5 minutes read.

Java Math getExponent() Method

The getExponent() method of Math class returns the unbiased exponent of the argument. Syntax: public static int getExponent (double d) Parameters: The parameter ‘d’ represents the double value. Return Value: The getExponent () method returns the...

1 minute read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.