回答編集履歴
4
間違っていたのを修正。manmanさんに感謝。
answer
CHANGED
@@ -1,12 +1,26 @@
|
|
1
1
|
jの上限はメモリが許す限りです。
|
2
|
-
```
|
2
|
+
```Ruby
|
3
3
|
require 'bigdecimal'
|
4
4
|
def dec_sum(n, i, j)
|
5
5
|
BigDecimal(1r/n, j+1).to_s[i+1..j+1].each_char.map(&:to_i).reduce(&:+)
|
6
6
|
end
|
7
7
|
# 使い方
|
8
8
|
puts dec_sum(7, 3, 8) # => 0.1428571428..のうち285714を全部足して27
|
9
|
-
puts dec_sum(97,2,96) #=> 431
|
9
|
+
puts dec_sum(97,2,96) #=> 431 ← これ、間違いです!
|
10
10
|
```
|
11
11
|
(修正)有効桁数は1つ多めにしないと四捨五入されちゃうときがある。
|
12
|
-
参考: [Ruby docs: library bigdecimal](http://docs.ruby-lang.org/ja/2.2.0/library/bigdecimal.html)
|
12
|
+
参考: [Ruby docs: library bigdecimal](http://docs.ruby-lang.org/ja/2.2.0/library/bigdecimal.html)
|
13
|
+
|
14
|
+
(追記) 間違っていました><
|
15
|
+
上のコードではE-nを考慮してなかったです。
|
16
|
+
E-n部分はmanmanさんの回答を参照して下さい。
|
17
|
+
で、BigDecimal#to_sに"F"渡すとEじゃなくなるので、それでの回答を
|
18
|
+
```Ruby
|
19
|
+
require 'bigdecimal'
|
20
|
+
def dec_sum(n, i, j)
|
21
|
+
BigDecimal(1r/n, j+1).to_s("F")[i+1..j+1].each_char.map(&:to_i).reduce(&:+)
|
22
|
+
end
|
23
|
+
# 使い方
|
24
|
+
puts dec_sum(7, 3, 8) # => 0.1428571428..のうち285714を全部足して27
|
25
|
+
puts dec_sum(97,2,96) #=> 432
|
26
|
+
```
|
3
改行
answer
CHANGED
@@ -8,4 +8,5 @@
|
|
8
8
|
puts dec_sum(7, 3, 8) # => 0.1428571428..のうち285714を全部足して27
|
9
9
|
puts dec_sum(97,2,96) #=> 431
|
10
10
|
```
|
11
|
+
(修正)有効桁数は1つ多めにしないと四捨五入されちゃうときがある。
|
11
|
-
|
12
|
+
参考: [Ruby docs: library bigdecimal](http://docs.ruby-lang.org/ja/2.2.0/library/bigdecimal.html)
|
2
修正部分の説明を正確に表記
answer
CHANGED
@@ -8,4 +8,4 @@
|
|
8
8
|
puts dec_sum(7, 3, 8) # => 0.1428571428..のうち285714を全部足して27
|
9
9
|
puts dec_sum(97,2,96) #=> 431
|
10
10
|
```
|
11
|
-
(修正)有効桁数は1つ多めにしないと四捨五入されちゃう
|
11
|
+
(修正)有効桁数は1つ多めにしないと四捨五入されちゃうときがある。参考: [Ruby docs: library bigdecimal](http://docs.ruby-lang.org/ja/2.2.0/library/bigdecimal.html)
|
1
有効桁数は一つ多めにしないと
answer
CHANGED
@@ -2,8 +2,10 @@
|
|
2
2
|
```
|
3
3
|
require 'bigdecimal'
|
4
4
|
def dec_sum(n, i, j)
|
5
|
-
BigDecimal(1r/n, j).to_s[i+1..j+1].each_char.map(&:to_i).reduce(&:+)
|
5
|
+
BigDecimal(1r/n, j+1).to_s[i+1..j+1].each_char.map(&:to_i).reduce(&:+)
|
6
6
|
end
|
7
7
|
# 使い方
|
8
|
-
puts dec_sum(7, 3, 8) # => 0.
|
8
|
+
puts dec_sum(7, 3, 8) # => 0.1428571428..のうち285714を全部足して27
|
9
|
+
puts dec_sum(97,2,96) #=> 431
|
9
|
-
```
|
10
|
+
```
|
11
|
+
(修正)有効桁数は1つ多めにしないと四捨五入されちゃうっぽい
|