Q:

print prime numbers in java in a simple way

I want to make a code to print all prime numbers .. I did this code in java .. I have a problem in my if statement in the isPrime method , I do not know how to implement it .. here is the code
public class PrimeList {

    private boolean [] numbers;

    /** Creates a complete filled out, the prime list of the numbers from 1 to n */
    public PrimeList(int n) {

        numbers = new boolean [n];
    }
    /** Prints all primes found */
    public void printPrimeList() {
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<numbers.length; i++) {
        if(isPrime(i)==true) {
            sb.append(i +",");
        }
        }
        System.out.print(sb.toString());
        }

    /** Returns true if the NBR is a prime number that is listed,
    false in all other cases */
    public boolean isPrime(int nbr) { 
        if(nbr == 2) {
            return true;
        } else if (nbr/2 gives an int number && nbr/3 gives an int number ) {
            return false;
        } else {
            return true;
        }

    }

    public static void main(String[] args) {

        PrimeList primes = new PrimeList(100);
        primes.printPrimeList();

    }
}

As you see this line else if (nbr/2 gives an int number && nbr/3 gives an int number ) { I do not know how to implement it ??
please help me to implement this if statement ..
thanks :)

A:

Essentially what you want to do is iterate over all integers x up to the squareroot of nbr and check if the remainder of nbr / x is 0.
To get the remainder of a division operation, you must use the modulus operator %.
Example:
for (int i=2; i<=Math.sqrt(nbr); i++) {
    if (nbr % i == 0) {
        // we found a number that divides evenly into nbr without 
        // any remainder, therefore this number is not a prime.
        return false;
    }
} 
return true;

Will leave it as an exercise to figure out why you only need to iterate up to the square root.

