Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to fill an array with the first N prime numbers in Java

1 Answer

0 votes
import java.util.ArrayList;

public class Program {
    private static final int N = 10;

    public static boolean isPrime(int num) {
        for (int i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static void fillArrayListWithNPrimeNumbers(ArrayList<Integer> arr, int size) {
        int num = 1;
        
        for (int i = 0; i < size; i++) {
            while (!isPrime(++num)) {}
            
            arr.add(num);
        }
    }

    public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<>(N);
        
        fillArrayListWithNPrimeNumbers(arr, N);
        
        for (int i = 0; i < N; i++) {
            System.out.printf("%3d", arr.get(i));
        }
    }
}




/*
run:

  2  3  5  7 11 13 17 19 23 29
  
*/

 



answered Feb 17, 2024 by avibootz

Related questions

1 answer 83 views
1 answer 113 views
1 answer 161 views
1 answer 159 views
2 answers 202 views
...