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:
Reactive WebSockets with Spring 5
Hướng dẫn sử dụng biểu thức chính quy (Regular Expression) trong Java
Introduction to Apache Commons Text
ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize
Java Program to Represent Graph Using Adjacency Matrix
Overview of Spring Boot Dev Tools
Introduction to Using Thymeleaf in Spring
Java Program to Implement Trie
Mệnh đề Switch-case trong java
Java Program to Implement HashMap API
Hướng dẫn Java Design Pattern – Singleton
Introduction to PCollections
The StackOverflowError in Java
Biến trong java
Serialization và Deserialization trong java
Java Program to Implement Floyd-Warshall Algorithm
Java Program to Implement Leftist Heap
Using the Not Operator in If Conditions in Java
CyclicBarrier in Java
Guide to @JsonFormat in Jackson
Model, ModelMap, and ModelAndView in Spring MVC
Convert char to String in Java
Java Program to Implement Quick Sort Using Randomization
DynamoDB in a Spring Boot Application Using Spring Data
Spring Boot - Logging
Concurrent Test Execution in Spring 5
Java Program to Implement vector
Simple Single Sign-On with Spring Security OAuth2
Java Program to Implement Hash Tables with Linear Probing
The Difference Between map() and flatMap()
Hướng dẫn sử dụng Java Generics
Java Program to Implement Flood Fill Algorithm