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:
A Quick JUnit vs TestNG Comparison
Java Program to Implement Euclid GCD Algorithm
Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
Receive email using IMAP
Java Program to Find Maximum Element in an Array using Binary Search
Lớp TreeMap trong Java
Java Program to Check Cycle in a Graph using Graph traversal
Java Program to Implement Jarvis Algorithm
Disable DNS caching
Spring Security and OpenID Connect
Tránh lỗi NullPointerException trong Java như thế nào?
Java Program to Implement Efficient O(log n) Fibonacci generator
Giới thiệu Json Web Token (JWT)
How to Use if/else Logic in Java 8 Streams
Java Program to Solve TSP Using Minimum Spanning Trees
Introduction to Spring Data JPA
Using Java Assertions
Java Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach
Ignore Null Fields with Jackson
Java Program to Implement Cubic convergence 1/pi Algorithm
Spring Boot - Logging
Java Program to Perform Finite State Automaton based Search
Java Program to Find the Longest Path in a DAG
Reading an HTTP Response Body as a String in Java
Java Deep Learning Essentials - Yusuke Sugomori
Refactoring Design Pattern với tính năng mới trong Java 8
Java Program to Perform Sorting Using B-Tree
Java Program to Implement Knight’s Tour Problem
Logging a Reactive Sequence
HttpClient Basic Authentication
Java Program to Implement WeakHashMap API
How to Iterate Over a Stream With Indices