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:
Prevent Brute Force Authentication Attempts with Spring Security
Sử dụng Fork/Join Framework với ForkJoinPool trong Java
Intro to the Jackson ObjectMapper
Working With Maps Using Streams
Java Program to Implement Interpolation Search Algorithm
Spring Boot - Flyway Database
The Registration Process With Spring Security
An Introduction to Java.util.Hashtable Class
Java Program to Describe the Representation of Graph using Incidence Matrix
Xử lý ngoại lệ đối với trường hợp ghi đè phương thức trong java
Cài đặt và sử dụng Swagger UI
Java InputStream to String
Serialize Only Fields that meet a Custom Criteria with Jackson
Guide to the Volatile Keyword in Java
Introduction to Spring Data JDBC
Tránh lỗi NullPointerException trong Java như thế nào?
OAuth 2.0 Resource Server With Spring Security 5
Java Program to Print the Kind of Rotation the AVL Tree is Undergoing
Test a REST API with Java
A Guide to EnumMap
Phân biệt JVM, JRE, JDK
Java String to InputStream
Java Program to Implement Booth Algorithm
Một số tính năng mới về xử lý ngoại lệ trong Java 7
Serverless Functions with Spring Cloud Function
How to Read a File in Java
Java Program to Implement SimpeBindings API
Sắp xếp trong Java 8
Guide to CopyOnWriteArrayList
Custom JUnit 4 Test Runners
Creating Docker Images with Spring Boot
Thao tác với tập tin và thư mục trong Java