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 Implement LinkedTransferQueue API
Function trong Java 8
Lớp lồng nhau trong java (Java inner class)
Java Program to Find Whether a Path Exists Between 2 Given Nodes
Java Program to Implement Triply Linked List
Java Program to Implement the Hungarian Algorithm for Bipartite Matching
Consumer trong Java 8
Set Interface trong Java
Java Program to Implement Double Order Traversal of a Binary Tree
Java List UnsupportedOperationException
Java Program to Implement Quick Sort with Given Complexity Constraint
A Guide to WatchService in Java NIO2
Giới thiệu luồng vào ra (I/O) trong Java
Guide to CountDownLatch in Java
Tổng quan về ngôn ngữ lập trình java
Java Program to Find Number of Spanning Trees in a Complete Bipartite Graph
Spring Cloud AWS – Messaging Support
Java Program to Find the Number of Ways to Write a Number as the Sum of Numbers Smaller than Itself
Spring Boot - Rest Controller Unit Test
Period and Duration in Java
Spring Security Custom AuthenticationFailureHandler
Java Program to Find Inverse of a Matrix
JPA/Hibernate Persistence Context
Java Program to Search for an Element in a Binary Search Tree
Java Program to Implement Bucket Sort
Converting String to Stream of chars
Java Program to Use Boruvka’s Algorithm to Find the Minimum Spanning Tree
Injecting Prototype Beans into a Singleton Instance in Spring
Spring Security Login Page with React
How to Implement Caching using Adonis.js 5
Đồng bộ hóa các luồng trong Java
Loại bỏ các phần tử trùng trong một ArrayList như thế nào?