×

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a prime number is a natural number that divides evenly into the numbers 1 and itself by approximately two different natural numbers. Take note that 0 and 1 are not prime numbers. All other even numbers may be divided by 2, making the number 2 the only even prime number. 

There are two ways to find the nth Prime Number

1. Applying a Simple/Traditional Approach

2. Using Eratosthenes' Sieve as a Guide

Applying a Simple/Traditional Approach

The fundamental approach for finding the nth prime number. The steps are described below. 

  • Read from the operator an integer (num).
  • Put the (ct!=num) condition within the while loop. The variable c starts as 0 and counts all detected prime numbers.
  • For the next number check, add 1 to variable I (which had a value of 1).
  • Verify whether or not variable I am a prime.
  • If so, add one to the variable ct.

Filename: NthPrime1.java

//Program for finding the nth prime number
//importing the packages
import java.io.*;
import java. util.*;
import java. util.Scanner;  
public class NthPrime1
{  
public static void main(String[] args)   
{  
//Scanner class 
Scanner sc = new Scanner(System.in);  
System. out.print("Enter the number: ");  
// the number is read by the user
int num = sc.nextInt();   
int number=1, ct=0, i;  
while (ct < num)  
{  
number=number+1;  
for (i = 2; i <= number; i++)  
{   
// checks for numbers having 2 factors  
if (number % i == 0)   
{  
// if the condition becomes true, then exit out of the loop  
break;  
}  
}  
if (i == number)  
{  
// the value of ct is incremented to 1
ct = ct+1;  
}  
}  
// displaying the nth prime number
System.out.println("The " +num +"th prime number is: " + number);  
}  
}  

Output

Enter the number: 14
The 14th prime number is: 43

Explanation:

A user-input integer has been taken and stored in the variable num. The variable num has its value increased by 1 whereas if while loop returns true. The while loop is indefinite if the ct variable's value exceeds num.

When a condition is met, the variable number is divided by i each time, and the result is checked against 0.

After that, a for loop is created, and i is initialized with 2 to start it off. Until the i=number condition returns true, the for loop runs. The loop is broken, and the next line that determines whether or not i is equal to the number is executed if the result equals 0.

2. Using Eratosthenes' Sieve as a Guide

An ancient procedure known as the Sieve of Eratosthenes allows us to locate all prime numbers up to a certain value (limit). It does this by noting and recognizing the multiples of each prime number, beginning with the initial prime number (2). The resulting unmarked numbers are prime numbers once each prime's multiples have been designated composite (not prime) numbers. The method has a computational complexity of O(n) and consumes O(n) memory (nloglogn). The best case scenario for n<10,000,000 is that it is the most effective way of finding all prime numbers lower than n.

Approach

First, apply the Sieve of Eratosthenes procedure to locate all the prime numerals inside the specified range.

All prime numbers should be kept in a vector.

Return an element at the (N-1)th index in a vector for a given integer N.

Algorithm

  • Make a list of consecutive numbers in the range 2 to n.
  • Let t= 2. The initial prime number, 2, has been taken into consideration.
  • Each number larger than or equal to t2 itself should be marked in the list starting at t2, counting up in increments of t. There will be t(t+1), t(t+2), t(t+3), etc. in these values.
  • Identify the first higher-than-t number in the list which is not marked. Only stop if there is a number like that. If not, set t to this value (the subsequent prime), and proceed from step 3 as before.

All the numbers that are left after terminating the algorithm are prime.

 Filename: NthPrime2.java

//Program for finding the nth prime number
//importing the packages
import java.io.*;
import java.util.*;
import java.util.ArrayList;  
public class NthPrime2  
{  
// declaring the max size 
static int MAX_SIZE = 1000005;  
// an object is created for storing the prime numbers
static ArrayList numlist = new ArrayList();  
//implementing a static function that uses the Sieve of Eratosthenes method to determine the nth prime number 
static void findNthPrimeNumber()   
{   
// a boolean Array is created and initialized to 0  
// the value become false if it is not the prime number  
boolean [] IsPrimes = new boolean[MAX_SIZE];   
for(int i = 0; i < MAX_SIZE; i++)  
IsPrimes[i] = true;  
for (int t = 2; t * t < MAX_SIZE; t++)   
{   
// if the value of IsPrimes[t] is not changed
// then the number is prime  
if (IsPrimes[t] == true)   
{   
//identifies the multiples of p that are bigger than or equal to the square of that number 
//The values multiples of p and less than p to power 2 have already been indicated.
for (int i = t * t; i < MAX_SIZE; i += t)   
IsPrimes[i] = false;   
}   
}   
for (int t = 2; t < MAX_SIZE; t++)   
if (IsPrimes[t] == true)   
// the prime number is pushed to ArrayList  
numlist.add(t);  
}   
// main code
public static void main (String args[])   
{  
/// the function findNthPrimeNumber() calling 
findNthPrimeNumber();  
// the get() method will return the position value in the list 
System.out.println("The 6th prime number is " + numlist.get(5));  
System. out.println("The 24th prime number is " + numlist.get(23));  
System.out.println("The 1000th prime number is " + numlist.get(999));  
}  
}   

Output

The 6th prime number is 13
The 24th prime number is 89
The 1000th prime number is 7919

Related Topics

Java Write File

In this post, we'll examine various Java programming methods for writing into files. Since this class is character-oriented due to how it is used in file handling in Java, it...

4 minutes read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.

Bounded buffer problem in Java

The Bounded buffer Problem can also be called a Producer consumer problem. The problem covers two processes—the producer and the consumer—that share a single, fixed-size buffer that serves as a...

4 minutes read.

Why to use Enum in Java?

In this article, you will be acknowledged about the Enum in java, its uses and mainly its purpose. Enum has various functionalities. Each of them will be discussed. Enum In a computer...

3 minutes read.

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.

Java Destructors

Before knowing about Java destructors, let us know about constructors. If we understand the concept of the constructor, we can easily understand about destructor and also, we will get an...

3 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Java Static Keyword

It can be either said that static declares the value to be the same, not only in the instance of a class but also as the whole. To declare a variable...

6 minutes read.

Java Macros

Macros are additions to the JDK 7 compiler in Java. Compile time macros are added and supported. Macros are Java classes that are instantiated and executed during the compilation process....

2 minutes read.

Java Socket Programming

Java Socket Programming Socket programming is used for the communication between the applications, i.e., client and server running on different JRE may be connection-oriented or connectionless. The client program can be designed using the...

8 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

How to convert String to String array in Java

A String in Java is a thing that indicates a collection of letters. We must include the String class from java.lang package if we want to be using strings. An...

5 minutes read.