Efficient Prime Number Checking in Java: A Step-by-Step Guide

Sachin Rathod
Nov 15, 2023

--

public boolean isPrime(int n){
if(n <= 1){
return false;
}
for(int i = 2; i*i<n;i++){
if (n % i==0){
return false;
}
}
return true;
}

Here’s a breakdown of how it works:

  1. We start by checking the corner case where ’n’ is less than or equal to 1.
  2. Next, we loop from 2 up to the square root of ‘n.’
  3. If any number within this range divides ’n’ with no remainder, ’n’ is not prime.
  4. If no factor is found, we determine that ’n’ is prime.

Key Takeaways:

  • The algorithm only checks up to the square root of ‘n.’
  • The modulo operator (%) efficiently checks for factors.
  • Early return when a factor is found improves overall efficiency.

--

--