-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Segmented_Sieve.java
99 lines (70 loc) · 2.12 KB
/
Segmented_Sieve.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
Segmented sieve is used to print prime number in a given range(l,r).
*/
import java.util.ArrayList;
import java.util.Scanner;
public class Segmented_Sieve {
public static int MAX=1000000;
public static boolean prime[]=new boolean[MAX+1];
// Basic sieve returning a list of primes number less than or equal to MAX
public static ArrayList<Integer> sieve() {
// Marking all number as true initailly
for(int i=0;i<=MAX;i++) {
prime[i]=true;
}
// 0 and 1 are not prime , so marking them as false
prime[0]=prime[1]=false;
for(int i=2;i*i<=MAX;i++) {
// If the given number is prime
if(prime[i]==true) {
// Marking all its multiple as false
for(int j=i*i;j<=MAX;j+=i) {
prime[j]=false;
}
}
}
ArrayList<Integer> primeList=new ArrayList<Integer>();
for(int i=0;i<=MAX;i++){
if(prime[i]==true) {
primeList.add(i);
}
}
return primeList;
}
// Printing prime number in the given range l to r
public static void printPrimeInRange(long l,long r,ArrayList<Integer> primeList) {
boolean array[]=new boolean[(int)(r-l+1)];
for(int i=0;i<=(r-l);i++) {
array[i]=true;
}
for(int i=0;i<primeList.size()&&(long)primeList.get(i)*primeList.get(i)<=r;i++) {
int currentPrime=primeList.get(i);
// Finding nearest number greater than or equal to l which is divisible by currentPrimeNumber
int baseValue=(int)(l/currentPrime)*currentPrime;
if(baseValue<l) {
baseValue+=currentPrime;
}
for(int j=baseValue;j<=r;j+=currentPrime) {
array[(int)(j-l)]=false;
}
if(baseValue==currentPrime) {
array[(int)(baseValue-l)]=true;
}
}
for(int i=0;i<=(r-l);i++) {
if(array[i]==true) {
System.out.print((i+l)+" ");
}
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter lower limit : ");
long l=sc.nextLong();
System.out.println("Enter upper limit :");
long r=sc.nextLong();
ArrayList<Integer> primeList=sieve();
System.out.println("Prime Number in range " + l + " to "+ r +" are : ");
printPrimeInRange(l, r, primeList);
}
}