printing out prime numbers from array

Posted by landscape on Stack Overflow See other posts from Stack Overflow or by landscape
Published on 2009-12-28T12:51:59Z Indexed on 2010/05/06 6:28 UTC
Read the original article Hit count: 353

Filed under:
|
|
|

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

© Stack Overflow or respective owner

Related posts about java

Related posts about primes