Advertisement
prem

Untitled

Oct 22nd, 2014
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. /**
  2. * PrimeGenerator represents the sequence of prime numbers
  3. * less than a specified number.
  4. *
  5. */
  6. public class PrimeGenerator
  7. {
  8. private int limit;
  9. private int currentPrime;
  10.  
  11. /**
  12. * Creates a PrimeGenerator which can get primes up to the limit
  13. * @param limit the number that all the primes must be less than
  14. */
  15. public PrimeGenerator(int limit)
  16. {
  17. this.limit = limit;
  18. currentPrime = 2; //the first prime number
  19. }
  20.  
  21. public boolean isPrime(int n)
  22. {
  23.  
  24. if (n==1)
  25. {
  26. return false;
  27. }
  28.  
  29. if ( n ==2 )
  30. {
  31. return true;
  32. }
  33.  
  34. if (n % 2 == 0)
  35. {
  36. return false;
  37. }
  38.  
  39. for(int i = 3; i < n; i= i+2)
  40. {
  41. if (n%i == 0)
  42. {
  43. return false;
  44. }
  45. }
  46.  
  47. return true;
  48. }
  49.  
  50. public int nextPrime() {
  51. int number = -1;
  52. for(int i=currentPrime+1; i<limit; i++) {
  53. if(isPrime(i) == true) {
  54. number = i;
  55. return number;
  56. }
  57. }
  58. return number;
  59. }
  60.  
  61. public void setLimit(int newLimit)
  62. {
  63. limit = newLimit;
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement