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 Check Whether a Weak Link i.e. Articulation Vertex Exists in a Graph
Spring Boot with Multiple SQL Import Files
Java Program to Implement ConcurrentHashMap API
Compact Strings in Java 9
Spring Data Java 8 Support
Hướng dẫn Java Design Pattern – Observer
Tính trừu tượng (Abstraction) trong Java
Java Program to Implement Sorting of Less than 100 Numbers in O(n) Complexity
Java Program to Solve a Matching Problem for a Given Specific Case
Receive email by java client
Working with Network Interfaces in Java
More Jackson Annotations
Hướng dẫn Java Design Pattern – Interpreter
Running Spring Boot Applications With Minikube
Sorting Query Results with Spring Data
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
4 tính chất của lập trình hướng đối tượng trong Java
Java Program to Find Second Smallest of n Elements with Given Complexity Constraint
Removing all Nulls from a List in Java
So sánh HashSet, LinkedHashSet và TreeSet trong Java
Intro to the Jackson ObjectMapper
JWT – Token-based Authentication trong Jersey 2.x
Spring Boot - Application Properties
Java Program to Compute Cross Product of Two Vectors
Chuyển đổi giữa các kiểu dữ liệu trong Java
Java Program to Perform the Unique Factorization of a Given Number
Java Program to Create the Prufer Code for a Tree
Toán tử trong java
Java Program to Solve any Linear Equation in One Variable
Understanding Memory Leaks in Java
Java Program to Implement Kosaraju Algorithm
Check if a String is a Palindrome in Java