Advertisement
cd62131

Repeating Decimal

Oct 31st, 2018
672
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.48 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. def repeating_decimal(a, b)
  3.   x, r = a.divmod b
  4.   qs = []
  5.   rs = [r]
  6.   loop {
  7.     q, r = (r * 10).divmod b
  8.     qs << q
  9.     break if r == 0
  10.     if i = rs.index(r)
  11.       qs.insert i, '('
  12.       qs << ')'
  13.       break
  14.     else
  15.       rs << r
  16.     end
  17.   }
  18.   "#{x}.#{qs.join ''}"
  19. end
  20.  
  21. [*2..19].each {|e| puts "1/#{e} = #{repeating_decimal(1, e)}" }
  22. [[2, 3], [9, 11], [7, 12], [22, 7]].each {|e1, e2|
  23.   puts "#{e1}/#{e2} = #{repeating_decimal(e1, e2)}"
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement