R.Slana R.Slana - 6 months ago 15
Java Question

Prime number program does not work

I am trying to make a simple program in Java that would output all the prime numbers (skipping number 2) up to the number

n
. It doesn't work and I am out of ideas. If someone could take a look at my code and tell me what the problem is I would greatly appreciate it.

public class PrimeNum {

public static void main(String[] args) {
int n = 50;
int notAPrime = 0;

System.out.println("All prime numbers before number " +n+ " are : ");
for(int i = n; i > 2; i--){
for(int j = 2; j < i; j++){
if(i % j == 0){
notAPrime++;
}
}
if(notAPrime == 0){
System.out.println(i);
notAPrime = 0;
}
}
}
}

Answer

You are missing a "break" in your for loop.

public class primeNum {

    public static void main(String[] args) {
        int n=50;
        int notAPrime=0;

        System.out.println("All prime numbers before number " +n+ " are : ");
        for(int i=n; i>2; i--){
           for(int j=2; j<i; j++){
               if(i%j==0){
                  notAPrime++;
                  break; //your program is missing this statement
               }
            } 
            if(notAPrime==0){
               System.out.print(i + " ");                   
            }   
            notAPrime=0;     //In your program it is inside the if statement which makes it incorrect.
        }
    }
}

Output: All prime numbers before number 50 are : 47 43 41 37 31 29 23 19 17 13 11 7 5 3

You can make your program more efficient by making the following changes:

public class primeNum {

    public static void main(String[] args) {
        int n=50;
        int notAPrime=0;

        System.out.println("All prime numbers before number " +n+ " are : ");
        for(int i=n; i>2; i--){
           if(i%2==0){
               continue;
           }
           for(int j=3; j<i; j+=2){  
               if(i%j==0){
                  notAPrime++;
                  break;
               }
            } 
            if(notAPrime==0){
               System.out.print(i + " ");                   
            }   
            notAPrime=0;     
        }
    }
}