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:
Mapping a Dynamic JSON Object with Jackson
Java Program to Check if a Directed Graph is a Tree or Not Using DFS
Spring MVC Content Negotiation
A Quick Guide to Spring MVC Matrix Variables
Spring Boot - Application Properties
Interface trong Java 8 – Default method và Static method
REST Web service: Upload và Download file với Jersey 2.x
Java Program to Check Cycle in a Graph using Graph traversal
A Guide to EnumMap
OAuth2.0 and Dynamic Client Registration
Send an email using the SMTP protocol
Introduction to Liquibase Rollback
Lập trình mạng với java
HttpClient 4 – Follow Redirects for POST
Handling URL Encoded Form Data in Spring REST
Using Optional with Jackson
Java Program to Find Nearest Neighbor for Dynamic Data Set
Spring Security – security none, filters none, access permitAll
Java Program to Perform Searching Based on Locality of Reference
Java Program to Permute All Letters of an Input String
Java Program to Find All Pairs Shortest Path
Java Program to Find the Minimum Element of a Rotated Sorted Array using Binary Search approach
ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize
Limiting Query Results with JPA and Spring Data JPA
LIKE Queries in Spring JPA Repositories
Java Program to Implement Self Balancing Binary Search Tree
Custom Thread Pools In Java 8 Parallel Streams
Java Program to Check if a Given Graph Contain Hamiltonian Cycle or Not
HttpClient with SSL
Java Program to Perform LU Decomposition of any Matrix
A Guide to the ResourceBundle
Predicate trong Java 8