KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > prevayler > demos > demo1 > PrimeCalculator


1 package org.prevayler.demos.demo1;
2
3 import org.prevayler.Prevayler;
4
5
6 /**
7  * This is client code to the prevalent system. It does not need to be persisted.
8  */

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 JavaDoc {
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         /*int factor = 2;
45         candidate = candidate / 2;
46         while (factor < candidate) {
47             if (candidate % factor == 0) return false;
48             factor++;
49         }
50         return true;*/

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