Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * PrimeGenerator represents the sequence of prime numbers
- * less than a specified number.
- *
- */
- public class PrimeGenerator
- {
- private int limit;
- private int currentPrime;
- /**
- * Creates a PrimeGenerator which can get primes up to the limit
- * @param limit the number that all the primes must be less than
- */
- public PrimeGenerator(int limit)
- {
- this.limit = limit;
- currentPrime = 2; //the first prime number
- }
- public boolean isPrime(int n)
- {
- if (n==1)
- {
- return false;
- }
- if ( n ==2 )
- {
- return true;
- }
- if (n % 2 == 0)
- {
- return false;
- }
- for(int i = 3; i < n; i= i+2)
- {
- if (n%i == 0)
- {
- return false;
- }
- }
- return true;
- }
- public int nextPrime() {
- int number = -1;
- for(int i=currentPrime+1; i<limit; i++) {
- if(isPrime(i) == true) {
- number = i;
- return number;
- }
- }
- return number;
- }
- public void setLimit(int newLimit)
- {
- limit = newLimit;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement