简体   繁体   中英

How to find prime numbers in an array of random numbers?

I have a problem with finding prime numbers in an array of randomly generated integers.

I tried using the 'for' loop to go through every element in my array to check whether it's a prime number or not. Although it prints some ints from the array, they are not prime numbers.

public static void main(String[] args) {
        defineTable();
        printPrimeNumbers();
    }

    private static int[] tab;

    private static int[] defineTable(){
        tab = new int[100];
        for (int i = 0; i < tab.length; i++){
            tab[i] = randomFill();
        }
        return tab;
    }

    private static int randomFill (){
        Random rand = new Random();
        int randomInt = rand.nextInt();
        return randomInt;
    }


    private static void printPrimeNumbers(){
        boolean isPrime = true;
        for (int i = 0; i < tab.length; i++){
            int num = tab[i];
            for (int j = 2; j < num; j++){
                if (num % j == 0){
                    isPrime = false;
                    break;
                }
            }
            if(isPrime){
                System.out.println(num + " jest liczbą pierwszą.");
            }
        }
    }

Any solutions to this problem? I started learning Java 4 days ago on my own. So far everything goes well, I understand most of the basics. But this problem seems too complex for me, a beginner.

Edit: I translated most of the code's variables to English from Polish, as my native language is Polish, hope it's understandable.

You're only setting isPrime to true at the beginning of printPrimeNumbers . Once it finds the first composite number, it becomes false , and you never reset it to true again to test the next number.

when writing Java code, try to split the task into functions(should serve a single purpose only). For your code extract the logic of determining Prime into a separate method and pass the random number to check whether it's prime or not, if yes then print otherwise don't print or do nothing.

Please check the below code snippet

A simpler and efficient way to find the prime number

public static boolean isPrime(int n) {  
           if (n <= 1) {  
               return false;  
           }  
           for (int i = 2; i <= Math.sqrt(n); i++) {  
               if (n % i == 0) {  
                   return false;  
               }  
           }  
           return true;  
       }  


private static void printPrimeNumbers(){
        for (int i = 0; i < tab.length; i++){
        if(isPrime(tab[i])){ 
        System.out.println(tab[i] + " jest liczbą pierwszą.");
       } 

    }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM