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:
Number Formatting in Java
Spring Boot - Zuul Proxy Server and Routing
A Quick JUnit vs TestNG Comparison
Spring Cloud – Tracing Services with Zipkin
Hướng dẫn Java Design Pattern – Object Pool
Creating a Generic Array in Java
Một số nguyên tắc, định luật trong lập trình
wait() and notify() Methods in Java
Java TreeMap vs HashMap
Concrete Class in Java
Java Program to Implement Self organizing List
Java Program to Find Shortest Path Between All Vertices Using Floyd-Warshall’s Algorithm
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Converting Between an Array and a Set in Java
Java Program to Find Whether a Path Exists Between 2 Given Nodes
Server-Sent Events in Spring
Java Program to Implement Stack using Linked List
Java Program to Implement Triply Linked List
Hướng dẫn tạo và sử dụng ThreadPool trong Java
Java Program to Implement Quick sort
Java Program to Solve a Matching Problem for a Given Specific Case
Java Program to Find Transpose of a Graph Matrix
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
Check if there is mail waiting
Quick Guide to java.lang.System
Java Program to Perform Partial Key Search in a K-D Tree
Introduction to Spring Cloud OpenFeign
Hướng dẫn Java Design Pattern – Abstract Factory
Batch Processing with Spring Cloud Data Flow
Class Loaders in Java
Different Ways to Capture Java Heap Dumps
Java Program to Check Whether an Undirected Graph Contains a Eulerian Path