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