相关文章:
-
常规方法
private static boolean isPrime(int number) { if (number < 2) { return false; } for (int i = 2; i <= Math.sqrt(number); i++) { if (number % i == 0) { return false; } } return true; } private static List<Integer> getPrimeList1(int n) { if (n < 2) { return null; } List<Integer> list = new ArrayList<>(); for (int i = 2; i <= n ; i++) { if (isPrime(i)) { list.add(i); } } return list; } public static void main(String[] args) { System.out.println(getPrimeList1(100)); } // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
-
lambda方法
public static List<Integer> getPrimeList2(int n) { if (n < 2) { return null; } return IntStream.rangeClosed(2, n).boxed().collect(partitioningBy(i -> IntStream.rangeClosed(2, (int) Math.sqrt(i)).noneMatch(j -> i % j == 0))).get(true); } public static void main(String[] args) { System.out.println(getPrimeList2(100)); } // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]