Function to test for primality

A simple modulus based algorithm used in Java to find if the passed number is prime or not.
  1. private boolean IsPrime(int i)
  2. {
  3. if (i <= 1) return false;
  4. if (i == 2) return true;
  5. if (i % 2 == 0) return false;
  6. int n = (int)Math.round(Math.sqrt(i));
  7. for (int x = 3; x <= n; x += 2)
  8. {
  9.  // If it divides, it's not a prime
  10.  if (i % x == 0)
  11.  {
  12. return false;
  13.  }
  14. }
  15. // If we got to this point, the number is prime
  16. return true;
  17. }

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top