相关文章:
-
常规方法
private static List<double[]> getPythagoras1(int n) { List<double[]> list = new ArrayList<>(); for (int i = 1; i <= n; i++) { for (int j = i; j <= n; j++) { double sqrt = Math.sqrt(i * i + j * j); if (sqrt % 1 == 0 && sqrt <= n) { list.add(new double[]{i, j, sqrt}); } } } return list; } public static void main(String[] args) { getPythagoras1(20).forEach(data -> System.out.println(Arrays.toString(data))); } // [3.0, 4.0, 5.0] // [5.0, 12.0, 13.0] // [6.0, 8.0, 10.0] // [8.0, 15.0, 17.0] // [9.0, 12.0, 15.0] // [12.0, 16.0, 20.0]
-
lambda方法
private static List<double[]> getPythagoras2(int n) { return IntStream.rangeClosed(1, n).boxed().flatMap(i -> IntStream.rangeClosed(i, n) .mapToObj(j -> new double[]{i, j, Math.sqrt(i * i + j * j)}) .filter(data -> data[2] % 1 == 0 && data[2] <= n)).collect(toList()); } public static void main(String[] args) { getPythagoras2(20).forEach(data -> System.out.println(Arrays.toString(data))); } // [3.0, 4.0, 5.0] // [5.0, 12.0, 13.0] // [6.0, 8.0, 10.0] // [8.0, 15.0, 17.0] // [9.0, 12.0, 15.0] // [12.0, 16.0, 20.0]