I am trying to implement a code to check whether a given array of numbers is prime or not,
but when the number is not a prime number, the output displays "Prime" and "Not Prime" both answers. What is the mistake I did here and it is a pleasure to have an answer from you? Thank you in advance!
Here is my code.
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
int[] arr = new int[number];
for (int i = 0; i < number; i++) {
arr[i] = scan.nextInt();
}
for (int i = 0; i < number; i++) {
int num = arr[i];
for (int j = 2; j <= Math.sqrt(num); j++) {
if (num % j == 0 && num !=2) {
System.out.println(num + "Not prime");
break;
}
}
System.out.println(num +"Prime");
}
If you're interested in making your code a little more efficient you can go this route.
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20 };
for (int num : numbers) {
System.out.println(num + ((isPrime(num) ? " is" : " is not") + " a prime"));
}
private static boolean isPrime(int num) {
// two is a prime
if (num == 2) {
return true;
}
// numbers 1 or less or any even
// number (sans 2) are not primes
if (num <= 1 || num % 2 == 0) {
return false;
}
// Now you can check for odd divisors.
// and increment by 2 starting with 3.
for (int i = 3; i <= Math.sqrt(num); i+=2) {
if (num % i == 0) {
return false;
}
}
return true;
}