×

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

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 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.

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.

Java String startsWith() method

Java String startsWith() method checks whether current String starts with given prefix or not . Syntax: public boolean startsWith(String prefix) public boolean startsWith(String prefix, int offset) Parameters: prefix : It is sequence of character Returns: It returns...

2 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

How to Convert Decimal to Binary in Java

How to Convert Decimal to Binary in Java There are two methods to convert Decimal to Binary. Using toBinaryString() method Using user-defined logic Using Integer.toBinaryString() The toBinaryString() is a static method of Integer...

2 minutes read.

Difference between Static and Instance Methods in Java

Static Method in Java The static technique has a place with the class as opposed to the object of the course. These are intended to be divided between every one of...

10 minutes read.

Time Class Operation in Java

The Java SQL package includes the time class. This class is merely a lightweight wrapper for java. util. THANKS TO THE recognize BC API can recognize this as a SQL...

3 minutes read.

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

How to Create an Object in Java

How to Create an Object in Java An object can be defined as a run time entity that contains the blue printof the class. It means that all the member functions...

5 minutes read.

The Diamond Operator in Java 7

The Diamond operator is a comparatively recent Java operator originally developed in JDK 7 to enhance type identification and eliminate boilerplate Java code. The Diamond operator is characterized by a...

2 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Java String vs StringBuffer

Java String vs StringBuffer In this section, we will discuss the key differences between String and StringBuffer class. Before moving to the ahead in this section, let’s introduce with both classes. String...

4 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.