Wednesday, May 9, 2012

Checking Prime in java


      public class Prime {
            public boolean isPrime(int n) {
                  if (n < 2) {
                      return false;
                  }
                  if (n == 2) {
                      return true;
                  }
                  if (n % 2 == 0) {
                      return false;
                  }

                  int sqrt = (int) Math.sqrt(n);

                  for (int i = 3; i <= sqrt; i += 2) {
                        if (n % i == 0) {
                           return false;
                        }
                  }
                  return true;
            }
      }

No comments:

Post a Comment