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

Checking for prime numbers – problems with understanding code – Java

I have a program which checks whether a given number from 0 to 9999 is a prime number or not (It was provided as a sample solution):

public class Primzahl {
    public static void main(String[] args) {


        for (int i = 0; i < 10000; i++) {
            System.out.println(i + " " + isPrimzahl(i));
        }

        System.out.println();
    }

    public static boolean isPrimzahl(int zahl) {
        for (int i = 2; i < (zahl / 2 + 1); i++) {
            if (zahl % i == 0) {
                return false;

            }

        }
        return true;
    }
}



However, I am having problems with understanding parts of the code:

i < (zahl / 2 + 1)

How is this part working?

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

And:

  if (zahl % i == 0) {
                return false;

            }

With how many numbers is a given zahl checked in this program?

Edit: typo.

>Solution :

i < (zahl / 2 + 1)

This is just setting the upper bound of the loop to half of the input number. Operator precedence means it will divide zahl by 2 before adding 1. There is no chance that the number will divide by something more than half of its value, so the loop can terminate there if no divisor has been found.

  if (zahl % i == 0) {
     return false;
  }

This causes it to exit the loop if an exact divisor has been found. % is the modulus operator so zahl % i == 0 means that zahl divides exactly by i and so the number cannot be prime.

The program checks whether any numbers from 2 to zahl/2 (in increments of 1) divides exactly into the input number.

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