nth_digit_of_fraction.sf 741 B

12345678910111213141516171819202122
  1. #!/usr/bin/ruby
  2. # An efficient formula for computing the n-th decimal digit of a given fraction expression x/y.
  3. # Formula from:
  4. # https://stackoverflow.com/questions/804934/getting-a-specific-digit-from-a-ratio-expansion-in-any-base-nth-digit-of-x-y
  5. # See also:
  6. # https://projecteuler.net/problem=820
  7. func nth_digit_of_fraction(n,x,y,base=10) {
  8. idiv(base * powmod(base, n-1, y) * x, y) % base
  9. }
  10. say sum(1..7, {|k| nth_digit_of_fraction(7, 1, k) }) #=> 10
  11. say sum(1..100, {|k| nth_digit_of_fraction(100, 1, k) }) #=> 418
  12. assert_eq(nth_digit_of_fraction(5, 13, 7, 5), 3)
  13. assert_eq(nth_digit_of_fraction(6, 13, 7, 5), 2)
  14. assert_eq(nth_digit_of_fraction(7, 13, 7, 5), 4)
  15. assert_eq(nth_digit_of_fraction(8, 13, 7, 5), 1)