java 生成n个素数

 

//Generate n prime numbers

import java.util.Scanner;

public class Numbers {

    public static void main(String[] args) {
        int n, count = 0;
        Scanner ip = new Scanner(System.in);
        System.out.print("Enter the size of n: ");
        n = ip.nextInt();
        int i = 2;
        while (count <= n) {
            if (isPrime(i)) {
                count++;
                System.out.print(i + " ");
            }
            i++;
        }
        ip.close();
    }

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



OUTPUT:
Enter the size of n: 10
2 3 5 7 11 13 17 19 23 29 31

 

你可能感兴趣的:(java 生成n个素数)