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:
New Features in Java 12
The Difference Between Collection.stream().forEach() and Collection.forEach()
Custom Error Pages with Spring MVC
Giới thiệu Java 8
Debug a HttpURLConnection problem
Java Program to Perform Postorder Non-Recursive Traversal of a Given Binary Tree
Spring 5 and Servlet 4 – The PushBuilder
Spring Cloud Bus
Working with Tree Model Nodes in Jackson
Java Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm
Hamcrest Collections Cookbook
Java Program to Implement AA Tree
Java Program to Implement Hopcroft Algorithm
Retrieve User Information in Spring Security
Send email with authentication
Reversing a Linked List in Java
HttpClient 4 – Send Custom Cookie
Control Structures in Java
Java Program to Implement Meldable Heap
Jackson Ignore Properties on Marshalling
Spring Security OAuth2 – Simple Token Revocation
Spring Boot - Building RESTful Web Services
Guava – Join and Split Collections
Java Program to Create a Random Graph Using Random Edge Generation
Java Program to Perform Partition of an Integer in All Possible Ways
Java Program to Implement Attribute API
Tránh lỗi NullPointerException trong Java như thế nào?
Anonymous Classes in Java
String Operations with Java Streams
Java Program to Implement an Algorithm to Find the Global min Cut in a Graph
Java Program to Generate Random Numbers Using Middle Square Method
Predicate trong Java 8