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 Program to Find Median of Elements where Elements are Stored in 2 Different Arrays
Hướng dẫn kết nối cơ sở dữ liệu với Java JDBC
Java Program to Perform Insertion in a BST
Guide to the Synchronized Keyword in Java
Java Program to Implement Dijkstra’s Algorithm using Queue
Java Timer
Spring Boot - Rest Controller Unit Test
So sánh HashMap và HashSet trong Java
Lập trình mạng với java
Java Program to Implement Direct Addressing Tables
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Spring Boot Integration Testing with Embedded MongoDB
The Dining Philosophers Problem in Java
Read an Outlook MSG file
Lập trình đa luồng trong Java (Java Multi-threading)
Circular Dependencies in Spring
Java – Byte Array to Reader
Find the Registered Spring Security Filters
Convert a Map to an Array, List or Set in Java
Java Program to Implement Treap
Using Java Assertions
Java Program to Implement Warshall Algorithm
Overflow and Underflow in Java
Java Program to Implement Meldable Heap
Java Program to Implement Stack using Two Queues
Model, ModelMap, and ModelAndView in Spring MVC
Arrays.asList vs new ArrayList(Arrays.asList())
Period and Duration in Java
Java equals() and hashCode() Contracts
New Features in Java 13
Java Program to Implement the MD5 Algorithm
Java Program to Find the Minimum Element of a Rotated Sorted Array using Binary Search approach