Tuesday, April 17, 2018

How to check prime number ?

  1. public class PrimeNumberAlgorithm {
  2. public static void main(String[] args) {
  3. isPrimeNumber(11);
  4. }
  5. private static void isPrimeNumber(int n) {
  6. boolean isPrime = true;
  7. int m = n / 2;
  8. for (int i = 2; i <= m; i++) {
  9. if (n % i == 0) {
  10. isPrime = false;
  11. break;
  12. }
  13. }
  14. System.out.println(isPrime == true ? "Prime number !!" : "Not prime number !!");
  15. }
  16. }
Output: Prime number !!
Time complexity is O(n/2)

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...