R.Slana - 4 months ago 6x

Java Question

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`

`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;
}
}
}
```

Source (Stackoverflow)

Comments