Skip to content

Instantly share code, notes, and snippets.

@kuwa72
Last active February 6, 2018 17:53
Show Gist options
  • Save kuwa72/6dee680fdb08091929a9ce492f08148d to your computer and use it in GitHub Desktop.
Save kuwa72/6dee680fdb08091929a9ce492f08148d to your computer and use it in GitHub Desktop.
Naive implement n/1 enumerator.
class Reciprocal
include Enumerable
def initialize(i)
@denon = i
end
def each
numer = 1
nums = []
loop do
q,r = numer.divmod(@denon)
if (q == 0 && (nums.all?(0) || nums.empty?)) || q != 0
nums << q
yield q
end
if q == 0
numer *= 10
redo
end
break if r == 0
numer = r
end
return nums
end
end
@kuwa72
Copy link
Author

kuwa72 commented Feb 6, 2018

Class of pure implementation of reciprocal numbers.
It's enumerable.
You can get never ending numbers if you want.

ruby -e 'p Reciprocal.new(7).to_enum.take(100)'
[0, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5, 7,1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8]

Benchmark

Benchmark.bm do |bm|
  bm.report { Reciprocal.new(7).to_enum.take(1000) }
  bm.report { Reciprocal.new(7).to_enum.take(10000) }
  bm.report { Reciprocal.new(7).to_enum.take(100000) }
  bm.report { Reciprocal.new(7).to_enum.take(1000000) }
  bm.report { Reciprocal.new(7).to_enum.take(10000000) }
end
       user     system      total        real
   0.001078   0.000066   0.001144 (  0.001136)
   0.012444   0.000422   0.012866 (  0.014372)
   0.087633   0.002223   0.089856 (  0.093306)
   0.832047   0.014849   0.846896 (  0.859842)
   8.623119   0.231629   8.854748 (  9.931088)

思ったより速い。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment