printing out prime numbers from array

老子叫甜甜 提交于 2019-12-20 06:28:48

问题


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

回答1:


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.)




回答2:


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.



来源:https://stackoverflow.com/questions/1969330/printing-out-prime-numbers-from-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!