-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimeParallel.java
More file actions
79 lines (69 loc) · 2.19 KB
/
PrimeParallel.java
File metadata and controls
79 lines (69 loc) · 2.19 KB
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
public class PrimeParallel extends Prime{
Thread[] threads;
static int nThreads;
PrimeParallel(long maxPrime){
super(maxPrime);
this.nThreads = Runtime.getRuntime().availableProcessors();
System.out.println("Nthread: " + nThreads);
}
PrimeParallel(long maxPrime, int nThreads){
super(maxPrime);
this.nThreads = nThreads;
System.out.println("Nthread: " + nThreads);
}
// finds primes with eratosthenes
@Override
public void findPrimes(){
threads = new Thread[nThreads];
int nThreadsMade = 0;
long start = 0;
long temp = bitArr.getLength()/nThreads;
long end = temp;
System.out.println("Maxprime " + maxPrime);
for(int i = 0; i < nThreads; i++){
if (i == (nThreads-1)){
end = bitArr.getLength();
}
threads[i] = new Thread(new ParallelCrossOut(start, end));
threads[i].start();
nThreadsMade++;
start = end;
end += temp;
}
joinThreads(nThreadsMade);
}
//Joins the threads
private void joinThreads(int nThreadsMade){
for (int i = 0; i < nThreadsMade; i++){
try{
threads[i].join();
} catch (InterruptedException e){
return;
}
}
}
private class ParallelCrossOut implements Runnable{
long start, end;
ParallelCrossOut(long start, long end){
this.start = (start*16)+1;
this.end = (end*16)+1;
}
public void run(){
long sqrtMaxPrime = (long)Math.sqrt(maxPrime);
for (long k = STARTPRIME; k <= sqrtMaxPrime; k +=2){
if(isPrime(k)){
long product = k*k;
long crossOut = product;
long k2 = k*2;
if (start > product){
crossOut = start + (k2 - ((start - product)%k2));
}
while (crossOut < end){
crossOut(crossOut);
crossOut +=k2;
}
}
}
}
}
}