Search code examples
javaprimes

issue in loop of finding prime number in java


I know the mistake here is in the for loop as it should be i=2 but if i put it as i=1 then why is it not entering in the loop .could someone dry run this code and tell me how exactly is this an issue

       if(n==2)
        { return true;} 

      for(int i=1;i<=Math.sqrt(n);i++){
        if(n % i == 0){
            return false;
        }
    }
    return true;

Solution

  • First you need to understand the mathematics behind it. Any number (that is a whole number, without a fraction part like for example 1.5) will give the reminder 0 when divided by one:

    n % 1 == 0
    

    This condition will therefore always be true. If your case, once you are at n = 1, you return false. I suggest you print out the output at every line of your program, and you will see the behavior.