printing out prime numbers from array
- by landscape
I'd like to print out all prime numbers from an array with method. I can do it with one int
but don't know how to return certain numbers from array. Thanks for help!
public static boolean isPrime(int [] tab) {
boolean prime = true;
for (int i = 3; i <= Math.sqrt(tab[i]); i += 2)
if (tab[i] % i == 0) {
prime = false;
break;
}
for(int i=0; i<tab.length; i++)
if (( tab[i]%2 !=0 && prime && tab[i] > 2) || tab[i] == 2) {
return true;
} else {
return false;
}
//return prime;
}
thanks both of you. Seems like its solved:
public static void isPrime(int[] tab) {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public static boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}