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:
Java Program to Implement Rolling Hash
Posting with HttpClient
Primitive Type Streams in Java 8
Guide to Mustache with Spring Boot
Collection trong java
Java Program to Implement Fibonacci Heap
Spring REST API with Protocol Buffers
Hướng dẫn Java Design Pattern – Command
Java Program to Implement Gauss Jordan Elimination
Jackson Ignore Properties on Marshalling
Phương thức tham chiếu trong Java 8 – Method References
A Guide to JPA with Spring
Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
Intro to the Jackson ObjectMapper
Java Program to Implement Floyd-Warshall Algorithm
Mix plain text and HTML content in a mail
How to Read a File in Java
Jackson – JsonMappingException (No serializer found for class)
Getting Started with Custom Deserialization in Jackson
Java 8 StringJoiner
Java Program to Implement Bit Array
Guide to Escaping Characters in Java RegExps
Java Program to Find All Pairs Shortest Path
Hướng dẫn sử dụng Java Annotation
Java Program to Optimize Wire Length in Electrical Circuit
Spring Boot - Admin Client
Using the Map.Entry Java Class
Hướng dẫn sử dụng biểu thức chính quy (Regular Expression) trong Java
Guava Collections Cookbook
Sorting Query Results with Spring Data
Date Time trong Java 8
Java Program to Implement Sieve Of Atkin