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:
JWT – Token-based Authentication trong Jersey 2.x
Wiring in Spring: @Autowired, @Resource and @Inject
Abstract class và Interface trong Java
Java Program to Implement Attribute API
Java Program to Implement Regular Falsi Algorithm
Comparing Arrays in Java
New Features in Java 15
Quick Guide to Spring Bean Scopes
How to Get the Last Element of a Stream in Java?
Spring Security Logout
Java Program to Implement Bellman-Ford Algorithm
Java Program to Represent Graph Using 2D Arrays
Debug a JavaMail Program
Map to String Conversion in Java
Feign – Tạo ứng dụng Java RESTful Client
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
Server-Sent Events in Spring
Convert char to String in Java
Custom HTTP Header with the HttpClient
Java Program to Construct an Expression Tree for an Postfix Expression
Hướng dẫn Java Design Pattern – Prototype
Debug a HttpURLConnection problem
Interface trong Java 8 – Default method và Static method
Spring Cloud Connectors and Heroku
Java Program to Implement Triply Linked List
Spring Boot - Tomcat Port Number
Sorting Query Results with Spring Data
Removing all duplicates from a List in Java
Java Program to Implement HashSet API
ETL with Spring Cloud Data Flow
Giới thiệu Json Web Token (JWT)
Creating Docker Images with Spring Boot