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 Collections Interview Questions
Java – Random Long, Float, Integer and Double
Java Program to Implement Queue using Linked List
Hướng dẫn Java Design Pattern – DAO
Java Program to Generate All Possible Combinations Out of a, b, c, d, e
JUnit5 Programmatic Extension Registration with @RegisterExtension
Java Program to Use Dynamic Programming to Solve Approximate String Matching
A Guide to Java HashMap
Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
Hướng dẫn tạo và sử dụng ThreadPool trong Java
Chương trình Java đầu tiên
Allow user:password in URL
Implementing a Runnable vs Extending a Thread
Java Program to Implement LinkedBlockingDeque API
Java Program to Implement Graph Coloring Algorithm
JUnit 5 for Kotlin Developers
Java Program to Generate Randomized Sequence of Given Range of Numbers
Call Methods at Runtime Using Java Reflection
Returning Custom Status Codes from Spring Controllers
Annotation trong Java 8
Spring Cloud Series – The Gateway Pattern
Java Program to Permute All Letters of an Input String
Java Program to Check Whether a Weak Link i.e. Articulation Vertex Exists in a Graph
A Guide to Spring Cloud Netflix – Hystrix
Guide To CompletableFuture
Custom JUnit 4 Test Runners
Java Program to implement Associate Array
Spring Boot - Internationalization
Các chương trình minh họa sử dụng Cấu trúc điều khiển trong Java
Java Program to Implement Cartesian Tree
Lớp Properties trong java
Java Program to Implement Park-Miller Random Number Generation Algorithm