Tuesday, August 9, 2016

Prime Number Program Java

Hi, it's have been long time since my latest post about Luhn Algorithm.
Today, I will show you how to create prime number program with Java.


What is prime number?
A prime number is a whole number greater than 1, whose only two whole-numberfactors are 1 and itself. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29.


How to check if given number X is prime or not?
This method will return true if X is prime and return false if X is not prime.
Time complexity for this algorithm are O( sqrt(X) ).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public boolean isPrime(int x) {
 if(x<2) return false;
 if(x==2 || x==3) return true;
 if(x%2==0 || x%3==0) return false;
 for(int p=6; (p-1) * (p-1) <= x; p += 6) {
  if(x % (p-1) == 0 ) return false;
  if(x % (p+1) == 0 ) return false;
 }
 return true;
}


How to generate prime number between A and B inclusive?
A must be less than or equal B.
Time complexity for this algorithm are O( range * sqrt(range) ), where range = B - A

1
2
3
4
5
6
7
8
9
public List<Integer> genPrimes(int a, int b) {
 List<Integer> primes = new ArrayList<Integer>();
 if(a<= 2) primes.add(2);
 if(a % 2 == 0) a++;
 for(int p=a; p<=b; p+=2) {
  if(isPrime(p)) primes.add(p);
 }
 return primes;
}


If you want faster algorithm, please check my other post:


Feel free to add your question or comment. 
For urgent request please send email to algojava8@gmail.com

No comments:

Post a Comment