Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

First you need to understand the mathematics behind it. Any number (that is a whole positive number) 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading