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 String to InputStream
Setting the Java Version in Maven
Java Program to Implement PrinterStateReasons API
Java Program to implement Bi Directional Map
Java Program to Find the Mode in a Data Set
Introduction to Spring MVC HandlerInterceptor
Cơ chế Upcasting và Downcasting trong java
Spring Boot - Code Structure
Guide to the Fork/Join Framework in Java
Java Program to Check if a Matrix is Invertible
Guide to System.gc()
Java Program to Implement ArrayList API
Java Program to Implement Threaded Binary Tree
Mảng (Array) trong Java
Jackson Date
Intro to the Jackson ObjectMapper
Converting String to Stream of chars
Java Program to Perform Naive String Matching
Java Program to Implement LinkedBlockingDeque API
Spring REST with a Zuul Proxy
Period and Duration in Java
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Java Program to Implement Dijkstra’s Algorithm using Queue
A Guide to HashSet in Java
Java InputStream to String
Spring Security – security none, filters none, access permitAll
Chuyển đổi Array sang ArrayList và ngược lại
Java Program to Implement Interpolation Search Algorithm
Exploring the Spring Boot TestRestTemplate
Tips for dealing with HTTP-related problems
Java Program to Check Whether a Given Point is in a Given Polygon
Mapping a Dynamic JSON Object with Jackson