Friday, 17 November 2017

Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range


Code:

import java.util.LinkedList;
import java.util.Scanner;

public class Sieve_Method
{
    public static LinkedList sieve(int n)
    {
        if(n < 2) 
            return new LinkedList();

        LinkedList primes = new LinkedList();
        LinkedList nums = new LinkedList();

        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:

Enter the upper bound : 
70
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67]



More Java Programs:








100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...