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:
A Guide to Java 9 Modularity
Java Program to Implement the Vigenere Cypher
Predicate trong Java 8
Java Program to Implement Binomial Heap
Spring REST API + OAuth2 + Angular (using the Spring Security OAuth legacy stack)
Java Program to Generate a Graph for a Given Fixed Degree Sequence
So sánh ArrayList và LinkedList trong Java
Debug a HttpURLConnection problem
Mockito and JUnit 5 – Using ExtendWith
Java Program to Solve a Matching Problem for a Given Specific Case
Java Program to Use Boruvka’s Algorithm to Find the Minimum Spanning Tree
Java Program to Implement Fenwick Tree
The Difference Between Collection.stream().forEach() and Collection.forEach()
Java Program to Implement Segment Tree
Java Program to implement Dynamic Array
The Registration Process With Spring Security
Wiring in Spring: @Autowired, @Resource and @Inject
Java Program to Implement Sorted Array
Serverless Functions with Spring Cloud Function
Java Program to Implement Trie
Show Hibernate/JPA SQL Statements from Spring Boot
REST Pagination in Spring
Number Formatting in Java
Java Program to Implement ConcurrentHashMap API
Vòng lặp for, while, do-while trong Java
Java – Delete a File
Java Program to do a Breadth First Search/Traversal on a graph non-recursively
Java Program to Implement Find all Back Edges in a Graph
Java Perform to a 2D FFT Inplace Given a Complex 2D Array
Ép kiểu trong Java (Type casting)
Hướng dẫn Java Design Pattern – MVC
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5