You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
2.0KB

  1. import java.math.BigInteger;
  2. /**
  3. * Worker class used in multithreading to check, whether a given number is a prime.
  4. */
  5. public class Worker extends Thread {
  6. private boolean isPrime;
  7. private BigInteger minVal;
  8. private BigInteger maxVal;
  9. private BigInteger candidate;
  10. private boolean finished = false;
  11. private String threadName ;
  12. public Worker(BigInteger candidate, BigInteger min, BigInteger max, String threadName) {
  13. this.minVal = min;
  14. this.maxVal = max;
  15. this.candidate = candidate;
  16. this.isPrime = true;
  17. this.threadName = threadName;
  18. //System.out.println("Created "+threadName+" for "+min+"-"+max+"");
  19. }
  20. /**
  21. * Returns a flag, indicating whether the prime candidate has a divisor in the given interval.
  22. * Since the thread might be still be running, it is important to check it first by using the
  23. * hasFinished() method.
  24. *
  25. * @return flag indicating whether there is a divisor or not
  26. */
  27. public boolean isPrime() {
  28. return this.isPrime;
  29. }
  30. /**
  31. * Returns if the thread has finished checking the given interval.
  32. *
  33. * @return the boolean
  34. */
  35. public boolean hasFinished() { return this.finished; }
  36. public void run() {
  37. BigInteger divCandidate = minVal;
  38. if (divCandidate.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO)){
  39. divCandidate = divCandidate.add(BigInteger.ONE);
  40. }
  41. while (divCandidate.compareTo(maxVal) < 1){ //divCandidate <= maxVal
  42. //System.out.println(this.threadName + " is testing "+divCandidate);
  43. if (candidate.mod(divCandidate).equals(BigInteger.ZERO)) {
  44. this.isPrime = false;
  45. this.finished = true;
  46. return;
  47. }
  48. divCandidate = divCandidate.add(BigInteger.ONE).add(BigInteger.ONE);
  49. }
  50. this.finished = true;
  51. // No divisor found, we are done for this interval
  52. }
  53. }