Reputation: 61
public class HelloWorld {
public static void main(String []args) {
int [] arr = {2, 5, 9, 6, 7, 13, 24, 42, 8};
int [] arr1 = new int[4];
int [] arr2 = new int[arr.length - arr1.length];
for(int i = 0; i < arr.length; i++) {
for(int j = 2; j <= arr[i]/2; j++) {
if(arr[i] % j == 0) {
System.out.println("Number is not prime " + arr[i]);
break;
}
else {
System.out.println("Number is prime " + arr[i]);
break;
}
}
}
}
}
The program should check an array of numbers and print if the given number is prime. There is something wrong, since the first 2 are not marked as prime. Then I don't know why 9 was taken as a prime number.
Upvotes: 3
Views: 1680
Reputation: 18255
for (int j = 2; j <= arr[i] / 2; j++) {
if (arr[i] % j == 0) {
System.out.println("Number is not prime " + arr[i]);
break;
} else {
System.out.println("Number is prime " + arr[i]);
break;
}
}
Here you iterate only once and check if given number is dividable by 2 or not (i.e. this is equal to arr[i] % 2 == 0
). To check if given number is prime or not, you have to check all numbers from 2 to sqrt(val).
I recommend you to select this check into separate method.
import java.util.function.IntPredicate;
final IntPredicate isPrime = val -> {
if (val < 2)
return false;
for (int i = 2, sqrt = (int)Math.sqrt(val); i <= sqrt; i++)
if (val % i == 0)
return false;
return true;
};
And your code looks much simpler:
int[] arr = { 2, 5, 9, 6, 7, 13, 2, 4, 42, 8 };
for (int val : arr) {
if (isPrime.test(val))
System.out.println("Number is prime " + val);
else
System.out.println("Number is not prime " + val);
}
Upvotes: 1
Reputation: 36
There are multiple problems in your code.
j <= arr[i]/2
is the culprit. According to this condition, j <= 1
and j == 2
. So, the loop does not get executed.Why 9 is taken as prime.
For the the first time when j == 2
and arr[i] == 9
. As, 9%2 != 0
, the number is printed as prime.
for(int j = 2; j <= arr[i]/2; j++){
if(arr[i] % j == 0){
System.out.println("Number is not prime " + arr[i]);
break;
}
else {
System.out.println("Number is prime " + arr[i]);
break;
}
}
Advice:
Instead of checking for arr[i]/2
, you can use square root of number to check instead.
You can refer the following program if needed:
public class PrimeNumber {
public static void main(String []args){
int [] arr = {2,3,4,5,9,6,7,13,24,42,8,400,101};
int [] arr1 = new int[4];
int [] arr2 = new int[arr.length - arr1.length];
boolean flag = true;
for(int i = 0; i < arr.length; i++){
if(arr[i] == 2 || arr[i] == 3 )
{
System.out.println("Number is prime " + arr[i]);
continue;
}
flag = true;
for(int j = 2; j <= Math.sqrt( arr[i] ); j++){
if(arr[i] % j == 0){
System.out.println("Number is not prime " + arr[i]);
flag = false;
break;
}
}
if ( flag )
{
System.out.println("Number is prime " + arr[i]);
}
}
}
}
Upvotes: 2
Reputation: 37
you need to remove this condition in your second for loop j <= arr[i]/2.
What you are looking for is j <= arr[i]
Upvotes: -1