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 Implement a Binary Search Algorithm for a Specific Search Sequence
Create a Custom Exception in Java
Java – Reader to String
Spring Boot Actuator
Java Program to Implement Pagoda
Spring Data MongoDB – Indexes, Annotations and Converters
Spring Security and OpenID Connect
Java 8 – Powerful Comparison with Lambdas
Spring MVC Content Negotiation
Spring Boot Change Context Path
Lớp TreeMap trong Java
Java TreeMap vs HashMap
File Upload with Spring MVC
Java 8 Stream findFirst() vs. findAny()
Exception Handling in Java
Generate a String
New in Spring Security OAuth2 – Verify Claims
Setting Up Swagger 2 with a Spring REST API
Form Validation with AngularJS and Spring MVC
Java – Rename or Move a File
Java Program to Describe the Representation of Graph using Adjacency List
LIKE Queries in Spring JPA Repositories
Refactoring Design Pattern với tính năng mới trong Java 8
Spring Data Java 8 Support
Rate Limiting in Spring Cloud Netflix Zuul
Java Program to Check Cycle in a Graph using Graph traversal
Encode a String to UTF-8 in Java
The DAO with Spring and Hibernate
Spring 5 and Servlet 4 – The PushBuilder
LinkedHashSet trong Java hoạt động như thế nào?
How to Read HTTP Headers in Spring REST Controllers
How to Get a Name of a Method Being Executed?