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. }
Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

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

Back To Top