Print 50 primes in Java


#1

What is wrong with this code? It take forever to run. Thanks.

public class Print_Primes {

public static void main(String[] args){

    int count = 4;
    String prime = "2,3,5,7,";
    int number = 10;
    int divisor;
    boolean state = true;

    while(count < 51){
        for (divisor = 2; divisor <= (int)(Math.sqrt(number)); ++divisor){
            if(number % divisor == 0){
                state = false;
                break;
            }
        }
        if (state == true){
            prime += number + ".";
            ++count;
        }
        ++number;
    }
    System.out.println(prime);
}

}


#2

You're only adding to count if state == true, which might mean that it gets stuck at numbers that are false. Try adding to count anyway.