This is java program to implement Wheel Seive method to generate the prime numbers from 2 to the given limit. This algorithm reduces the time by checking only till n^2.
Here is the source code of the Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
//This is a sample program to print all the prime numbers between 2 and n
import java.util.LinkedList;
import java.util.Scanner;
public class Sieve_Method
{
public static LinkedList<Integer> sieve(int n)
{
if(n < 2)
return new LinkedList<Integer>();
LinkedList<Integer> primes = new LinkedList<Integer>();
LinkedList<Integer> nums = new LinkedList<Integer>();
for(int i = 2;i <= n;i++)
{ //unoptimized
nums.add(i);
}
while(nums.size() > 0)
{
int nextPrime = nums.remove();
for(int i = nextPrime * nextPrime;i <= n;i += nextPrime)
{
nums.removeFirstOccurrence(i);
}
primes.add(nextPrime);
}
return primes;
}
public static void main(String args[])
{
System.out.println("Enter the upper bound : ");
Scanner sc = new Scanner(System.in);
int end = sc.nextInt();
System.out.println(sieve(end));
sc.close();
}
}
Output:
$ javac Sieve_Method.java $ java Sieve_Method Enter the upper bound : 70 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67]
Related posts:
Ways to Iterate Over a List in Java
Xử lý ngoại lệ trong Java (Exception Handling)
Command-Line Arguments in Java
The Registration API becomes RESTful
Hướng dẫn Java Design Pattern – State
Java Program to Print the Kind of Rotation the AVL Tree is Undergoing
Lớp LinkedHashMap trong Java
A Guide to @RepeatedTest in Junit 5
Kiểu dữ liệu Ngày Giờ (Date Time) trong java
Java Program to Generate All Subsets of a Given Set in the Lexico Graphic Order
Hướng dẫn Java Design Pattern – Interpreter
Java Program to Give an Implementation of the Traditional Chinese Postman Problem
Từ khóa static và final trong java
Spring 5 WebClient
LIKE Queries in Spring JPA Repositories
@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll
Guide To CompletableFuture
Java Program to Implement Ternary Heap
OAuth2 for a Spring REST API – Handle the Refresh Token in AngularJS
Spring Boot - Actuator
Java – Write an InputStream to a File
Java Program to Implement Lloyd’s Algorithm
Check If a File or Directory Exists in Java
Working with Network Interfaces in Java
Java Program to Implement Bubble Sort
Phương thức tham chiếu trong Java 8 – Method References
Giới thiệu Aspect Oriented Programming (AOP)
Java Program to Create a Minimal Set of All Edges Whose Addition will Convert it to a Strongly Conne...
Java Program to Implement HashTable API
Java Program to Implement Slicker Algorithm that avoids Triangulation to Find Area of a Polygon
Java Program to Implement a Binary Search Tree using Linked Lists
Guide to the Java Clock Class