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:
Anonymous Classes in Java
Introduction to Spring Cloud CLI
Convert Character Array to String in Java
Spring REST API + OAuth2 + Angular
Spring Security Basic Authentication
Spring Web Annotations
A Guide to @RepeatedTest in Junit 5
Using Spring @ResponseStatus to Set HTTP Status Code
Spring Security – security none, filters none, access permitAll
Serialization và Deserialization trong java
Java Program to Implement Fisher-Yates Algorithm for Array Shuffling
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Spring Boot - CORS Support
How to Add a Single Element to a Stream
Java Program to Give an Implementation of the Traditional Chinese Postman Problem
How to Read HTTP Headers in Spring REST Controllers
Java Program for Topological Sorting in Graphs
Hướng dẫn Java Design Pattern – DAO
Spring Boot - Internationalization
Exception Handling in Java
Spring Boot - Admin Server
Java Program to Implement Gauss Seidel Method
Display Auto-Configuration Report in Spring Boot
Giới thiệu Json Web Token (JWT)
Java Program to Implement Euclid GCD Algorithm
OAuth 2.0 Resource Server With Spring Security 5
Guide to Java OutputStream
Hướng dẫn Java Design Pattern – Chain of Responsibility
Java 8 StringJoiner
Guide to Spring 5 WebFlux
Spring Security Form Login
Java Program to Compare Binary and Sequential Search