1 package org.prevayler.demos.demo1; 2 3 import org.prevayler.Prevayler; 4 5 6 9 class PrimeCalculator { 10 11 private final Prevayler _prevayler; 12 private final NumberKeeper _numberKeeper; 13 14 15 PrimeCalculator(Prevayler prevayler) { 16 _prevayler = prevayler; 17 _numberKeeper = (NumberKeeper)prevayler.prevalentSystem(); 18 } 19 20 21 void start() throws Exception { 22 int largestPrime = 0; 23 int primesFound = 0; 24 int primeCandidate = _numberKeeper.lastNumber() == 0 25 ? 2 26 : _numberKeeper.lastNumber() + 1; 27 28 while (primeCandidate <= Integer.MAX_VALUE) { 29 if (isPrime(primeCandidate)) { 30 31 _prevayler.execute(new NumberStorageTransaction(primeCandidate)); 32 33 largestPrime = primeCandidate; 34 primesFound = _numberKeeper.numbers().size(); 35 System.out.println("Primes found: " + primesFound + ". Largest: " + largestPrime); 36 } 37 38 primeCandidate++; 39 } 40 } 41 42 43 private boolean isPrime(int candidate) { 44 51 52 if (candidate < 2) { return false; } 53 if (candidate == 2) { return true; } 54 if (candidate % 2 == 0) { return false; } 55 56 int factor = 3; 57 double square = Math.ceil(Math.sqrt(candidate)); 58 while (factor <= square) { 59 if (candidate % factor == 0) return false; 60 factor+=2; 61 } 62 return true; 63 } 64 65 } | Popular Tags |