I am having trouble creating a method that will find out the number of prime integers in the array , so far i have done this but when i run it , it doesn't work properly it counts 2 as prime number and also other numbers . Any suggestions please?
int[] newSet = {8, 4, 22, 82, 12, 32, 18, 400, 3, 33, 401, -1, 1, 3, 9};
System.out.println(primeIntegers(newSet));
}
public static int primeIntegers(int[] numbers) {
int count = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 3 == 0) {
count++;
}
}
return count;
}
}
if (numbers[i] % 3 == 0)
definitely be wrong for determining a prime. Firstly , you need to know what a prime number is (2 is a prime number).
The easiest(not the best) way to determine if a number is a prime would be :
//checks whether an int is prime or not.
boolean static isPrime(int n) {
for(int i=2;i<n;i++) {//here,change i<n into 2*i<n or Math.sqrt(i)<n will be better
if(n%i==0)
return false;//can be dividable by not one or itself.
}
return true;
}
//use above method to count the prime number
public static int primeIntegers(int[] numbers) {
int count = 0;
for (int i = 0; i < numbers.length; i++) {
if(isPrime(numbers[i]))
count++;
}
}
return count;
}
The condition you are validating returns you only the numbers that are not divisible by 3 to make for finding the prime numbers you need to at least check for all the numbers less than its square root . ie.
boolean chkPrime(int num)
{
for(int i=2;i<(sqrt(num));i++)
if(num % i==0)
return false;
return true;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.