views:

162

answers:

2

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;
        }
    }
+2  A: 

I would suggest you separate this into two methods:

  • One method to determine whether a single number is prime
  • One method to iterate through an array, call the first method with each number, and print out the values for which the method returns true.

That separates out the two concerns neatly. If you're stuck on exactly how to do this, please give details of which bit you find hard. (I'm assuming this is homework, which is why I haven't just included the code.)

Jon Skeet
A: 

Assuming you have:

  • One array of integers, with some being prime and some being not prime.
  • A function for testing if one of those numbers is prime.

Simply iterate over the array, and for each number:

if (isPrime(n)) {
    system.out.println(n);
}

You probably don't want to try and do multiple ints at once, one at a time should be alot simpler to code.

Adam Luchjenbroers