質問するログイン新規登録

回答編集履歴

3

奇数の和の範囲の誤りを訂正

2019/10/08 10:49

投稿

xebme
xebme

スコア1113

answer CHANGED
@@ -1,14 +1,14 @@
1
1
  **和の公式**
2
2
 
3
- の和 (1 から n) n個 : n * (n + 1) / 2
3
+ 自然数の和 (1 から n) n個 : n * (n + 1) / 2
4
4
  偶数の和 (2 から 2n) n個 : n * (n + 1)
5
- 奇数の和 (1 から 2n+1) n個 : n ^ 2
5
+ 奇数の和 (1 から 2n-1) n個 : n ^ 2
6
6
 
7
7
  **ラムダ式**
8
8
 
9
9
  和の公式をラムダ式で表します。どれも 1 から n までの和。
10
10
  ```Java
11
- n -> n*(n+1)/2 // と偶数
11
+ n -> n*(n+1)/2 // 自然
12
12
  n -> (int)Math.pow(Math.ceil(n/2.0), 2)) // 奇数
13
13
  n -> (n/2)*(n/2)+(n/2) // 偶数
14
14
  ```
@@ -17,7 +17,7 @@
17
17
 
18
18
  x から y までの和は、和(y) - 和(x - 1)だから。
19
19
  ```Java
20
- BiFunction<Integer,Integer,Integer> diff(IntFunction<Integer> f) {
20
+ BiFunction<Integer,Integer,Integer> rangeSum(IntFunction<Integer> f) {
21
21
  return (x,y) -> f.apply(y) - f.apply(x-1);
22
22
  }
23
23
  ```
@@ -26,7 +26,32 @@
26
26
 
27
27
  1から5までの和の計算。1から1、2から2でも正しく計算します。
28
28
  ```Java
29
- diff(n -> n*(n+1)/2).apply(1,5); // と偶数
29
+ rangeSum(n -> n*(n+1)/2).apply(1,5); // 自然
30
- diff(n -> (int)Math.pow(Math.ceil(n/2.0), 2))).apply(1,5); // 奇数
30
+ rangeSum(n -> (int)Math.pow(Math.ceil(n/2.0), 2))).apply(1,5); // 奇数
31
- diff(n -> (n/2)*(n/2)+(n/2)).apply(1,5);// 偶数
31
+ rangeSum(n -> (n/2)*(n/2)+(n/2)).apply(1,5);// 偶数
32
+ ```
33
+
34
+ ###
35
+ **訂正 2019-10-08**
36
+ 奇数の和の範囲の誤りを訂正しました。
37
+ diffの名称をrangeSumに変更しました。
38
+
39
+ **追記 2019-10-08**
40
+
41
+ **合成関数(y < x にも対応)**
42
+
43
+ ```Java
44
+ BinaryOperator<Integer> maxBy = BinaryOperator.maxBy(Integer::compare);
45
+ BinaryOperator<Integer> minBy = BinaryOperator.minBy(Integer::compare);
46
+ BiFunction<Integer,Integer,Integer> rangeSum(IntFunction<Integer> f) {
47
+ return (x,y) -> f.apply(maxBy.apply(x,y)) - f.apply(minBy.apply(x,y)-1);
48
+ }
49
+ ```
50
+
51
+ **和の計算**
52
+
53
+ ```Java
54
+ rangeSum(n -> n*(n+1)*(2*n+1)/6).apply(1,5); // 自然数の二乗の和
55
+ rangeSum(n -> (int)Math.pow(n*(n+1)/2, 2)).apply(1,5); // 自然数の三乗の和
56
+
32
57
  ```

2

ラムダ式を修正

2019/10/08 10:49

投稿

xebme
xebme

スコア1113

answer CHANGED
@@ -26,7 +26,7 @@
26
26
 
27
27
  1から5までの和の計算。1から1、2から2でも正しく計算します。
28
28
  ```Java
29
- diff(n -> n*(n+1)/2)).apply(1,5); // 奇数と偶数
29
+ diff(n -> n*(n+1)/2).apply(1,5); // 奇数と偶数
30
30
  diff(n -> (int)Math.pow(Math.ceil(n/2.0), 2))).apply(1,5); // 奇数
31
31
  diff(n -> (n/2)*(n/2)+(n/2)).apply(1,5);// 偶数
32
32
  ```

1

ラムダ式の修正

2019/09/28 08:33

投稿

xebme
xebme

スコア1113

answer CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  和の公式をラムダ式で表します。どれも 1 から n までの和。
10
10
  ```Java
11
- n -> n*(n+1)/2) // 奇数と偶数
11
+ n -> n*(n+1)/2 // 奇数と偶数
12
12
  n -> (int)Math.pow(Math.ceil(n/2.0), 2)) // 奇数
13
13
  n -> (n/2)*(n/2)+(n/2) // 偶数
14
14
  ```