-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactorDriver.java
More file actions
96 lines (81 loc) · 2.47 KB
/
Copy pathFactorDriver.java
File metadata and controls
96 lines (81 loc) · 2.47 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import java.io.*;
import java.util.*;
/**
* Counts the number of factors of a large testNumber
* using 8 different threads.
*
* @author Jess Conway
* @version 02/05/2018
*/
class FactorChecker extends Thread {
private long threadNumber;
private long testNumber;
private int threads;
private int counter;
public FactorChecker(long threadNumber, long testNumber, int threads)
{
this.threadNumber = threadNumber;
this.testNumber = testNumber;
this.threads = threads;
}
public void run()
{
for(long k = threadNumber; k*k <= testNumber; k+=threads)
{
if(testNumber%k == 0)
counter += 2;
}
}
public int getCounter()
{
return counter;
}
}
class FactorDriver {
public static void main(String[] args)
{
Random randomGenerator = new Random();
int threads = 8;
FactorChecker[] thrd= new FactorChecker[8];
double sum;
double avg;
for(int i=12; i<=18; i++)
{
sum = 0;
for(int j=0; j<=10; j++)
{
long lowerBound = (long)Math.pow(10,i-1);
long upperBound = (long)Math.pow(10,i-1) + (long)Math.pow(10,i-1)-1;
long testNumber = lowerBound + (long)(randomGenerator.nextDouble()*(upperBound-lowerBound));
int counter = 0;
//Start clock
long startTime = System.nanoTime();
//Start calculation
for(int k = 0; k < threads; k++)
{
thrd[k] = new FactorChecker(k+1, testNumber, threads);
thrd[k].start();
}
for(int k=0;k<threads;k++)
{
try
{
thrd[k].join();
}
catch(InterruptedException e){}
counter += thrd[k].getCounter();
}
//Stop clock
long endTime = System.nanoTime();
//Calculate time elapsed
long timeElapsedInMilliseconds = (endTime - startTime) / 1000000;
//Print results
System.out.println("The number of factors of the number " + testNumber + " is " + counter + ".");
System.out.println("That calculation took " + timeElapsedInMilliseconds + " milliseconds.");
sum += timeElapsedInMilliseconds;
}
avg = sum/10;
System.out.println("The average time taken for a " + i + " digit number is " + avg + " ms.");
}
}
}