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:
Lớp TreeMap trong Java
Java Program to Implement Sparse Matrix
Java program to Implement Tree Set
Java Program to Implement Unrolled Linked List
Spring WebClient Requests with Parameters
Java Program to Solve Travelling Salesman Problem for Unweighted Graph
Spring Boot Security Auto-Configuration
Guide to the Java ArrayList
Java Program to Implement Knight’s Tour Problem
Hướng dẫn Java Design Pattern – Adapter
Java – File to Reader
String Initialization in Java
Java Program to Implement Park-Miller Random Number Generation Algorithm
Introduction to Eclipse Collections
Java Program to Implement Stack
Disable DNS caching
Extract links from an HTML page
Java Program to Find the Edge Connectivity of a Graph
Java Program to Implement Sieve Of Atkin
Collect a Java Stream to an Immutable Collection
OAuth 2.0 Resource Server With Spring Security 5
Jackson – Marshall String to JsonNode
Convert String to Byte Array and Reverse in Java
Java Program to Solve Set Cover Problem assuming at max 2 Elements in a Subset
Java Program to Implement ConcurrentHashMap API
Posting with HttpClient
How to Define a Spring Boot Filter?
Java Program to Generate All Subsets of a Given Set in the Lexico Graphic Order
Java Program to Implement Queue using Two Stacks
Một số tính năng mới về xử lý ngoại lệ trong Java 7
Java Program to Solve Knapsack Problem Using Dynamic Programming
Java Program to Implement Stein GCD Algorithm