×

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

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

Sum of digits in string in java

To find the sum of all digits in a string, you need to traverse through the string one by one character; if the character is an integer, you need to...

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

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

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

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

How to Reduce Time Complexity in Java

What is time complexity?  The time complexity in java is given as the amount of time a program requires to run or execute it Calculating the time complexity of the program The time...

4 minutes read.

How to Develop Programming Logic in Java?

Introduction In the world of software development, Java programming language is one of the most powerful programming languages that is used to create a wide range of applications. It includes desktop,...

18 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Composition in Java

Composition Java uses the composition method to implement a has-a connection. Composition allows us to reuse code in the same way that Java inheritance does. The "is-a" relationship is implemented using the...

3 minutes read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax: public int compareTo(String anotherString) Parameters: anotherString: the...

2 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.