Home > Software engineering >  Prime Number in Java - Output not displayed
Prime Number in Java - Output not displayed

Time:12-03

So, I've been trying to create a program that prints prime numbers by using the theory that a prime number should only have 2 factors. But when I try looping the number cannot be displayed. Why? Can anyone point out my mistakes?

public class NewClass {
    
    public static void main(String[] args){
        
        double factor;
        int x,y,counter = 0;
        for (x = 1; x <= 50; x  ){
            for (y = 1; y <= 50; y  ){
                factor = x%y;
                if (factor == 0){
                    counter  = 1;
                }
                else{
                    counter  = 0;
                }
            }
            if (counter == 2){
                System.out.println(x);}
        } 
    }
}
 

I was expecting that the numbers that have ONLY 2 factors should be printed out, but nothing happen. Please help me.

CodePudding user response:

There are a few issues with your code that are causing it not to work as expected:

  1. You are using a double data type for the factor variable, but a double is not necessary for this calculation - an int would be sufficient.

  2. You are incrementing the counter variable by 1 or 0 depending on whether the factor is 0 or not, but this will not give you the correct number of factors for a given number. Instead, you should only increment the counter if the factor is 0, and then check if the counter equals 2 after the inner loop has completed.

  3. You are only printing the number if the counter equals 2, but this means that you will only print numbers that have exactly 2 factors, which is not what you want - you want to print numbers that have only 2 factors. To do this, you need to reset the counter variable to 0 after each iteration of the outer loop, and then only print the number if the counter equals 2 after the inner loop has completed.

Here is how I would rewrite your code to fix these issues:

public class NewClass {
public static void main(String[] args){
    
    int factor;
    int x,y,counter = 0;
    for (x = 1; x <= 50; x  ){
        counter = 0; // reset the counter for each iteration of the outer loop
        for (y = 1; y <= 50; y  ){
            factor = x%y;
            if (factor == 0){
                counter  = 1;
            }
        }
        if (counter == 2){ // only print the number if it has only 2 factors
            System.out.println(x);
        }
    } 
}
}

With these changes, your code should print the prime numbers between 1 and 50 as expected.

  • Related