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:
How to Replace Many if Statements in Java
Guide to java.util.concurrent.BlockingQueue
Hướng dẫn Java Design Pattern – Command
Java Program to Solve the Fractional Knapsack Problem
Programmatic Transaction Management in Spring
Prevent Brute Force Authentication Attempts with Spring Security
Java Program to Implement Stack
LinkedHashSet trong java
Java 14 Record Keyword
Introduction to Apache Commons Text
Display Auto-Configuration Report in Spring Boot
A Guide To UDP In Java
Java Program to Implement Word Wrap Problem
Java Program to implement Bi Directional Map
Java Program to Give an Implementation of the Traditional Chinese Postman Problem
Exploring the Spring Boot TestRestTemplate
Java Program to Create a Minimal Set of All Edges Whose Addition will Convert it to a Strongly Conne...
Java Program to Implement TreeSet API
Java – String to Reader
So sánh HashMap và HashSet trong Java
Java Program to Implement Selection Sort
Java Program to Implement Binomial Heap
Java Program to Implement Quick Sort with Given Complexity Constraint
Java Program to Implement Find all Cross Edges in a Graph
How to Add a Single Element to a Stream
Java Program to Implement VList
Spring Boot - Cloud Configuration Server
A Guide to Queries in Spring Data MongoDB
Java Program to Implement Leftist Heap
Setting Up Swagger 2 with a Spring REST API
Assertions in JUnit 4 and JUnit 5
Configure a Spring Boot Web Application