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:
Mệnh đề if-else trong java
Working with Tree Model Nodes in Jackson
Java Program to Implement LinkedBlockingQueue API
Hướng dẫn sử dụng Java Generics
Jackson – Change Name of Field
Summing Numbers with Java Streams
Build a REST API with Spring and Java Config
Java Program to Check whether Directed Graph is Connected using DFS
CyclicBarrier in Java
Tổng quan về ngôn ngữ lập trình java
Java Program to Implement Heap
Java Program to Find MST (Minimum Spanning Tree) using Prim’s Algorithm
A Guide to LinkedHashMap in Java
Hướng dẫn Java Design Pattern – Facade
Working with Kotlin and JPA
Java Program to Implement Bit Array
Java toString() Method
Thao tác với tập tin và thư mục trong Java
Java 8 and Infinite Streams
So sánh HashMap và Hashtable trong Java
Comparing Objects in Java
HttpClient with SSL
Java Program to Implement Extended Euclid Algorithm
Immutable Map Implementations in Java
Java Program to Implement Find all Back Edges in a Graph
So sánh ArrayList và LinkedList trong Java
Spring Cloud AWS – Messaging Support
Java Program to Check Whether a Directed Graph Contains a Eulerian Cycle
Java Program to Implement CountMinSketch
Java Program to Generate Random Numbers Using Multiply with Carry Method
Transaction Propagation and Isolation in Spring @Transactional
Sử dụng JDBC API thực thi câu lệnh truy vấn dữ liệu