champernowne_constant_nth_digit.sf 706 B

12345678910111213141516171819202122
  1. #!/usr/bin/ruby
  2. # Compute the nth-digit in the decimal expansion of the Champernowne constant.
  3. # Formula due to David W. Cantrell (Feb 18 2007)
  4. # See also:
  5. # https://oeis.org/A033307
  6. # https://en.wikipedia.org/wiki/Champernowne_constant
  7. func champernowne_nth_digit(n) {
  8. var i = ceil(LambertW(log(10) / 10**(1/9) * (n - 1/9))/log(10) + 1/9)
  9. floor((10**((n + (10**i - 10)/9) % i - i + 1) * ceil((9*n + 10**i - 1)/(9*i) - 1)) % 10)
  10. }
  11. say { champernowne_nth_digit(_) }.map(1..25)
  12. say { champernowne_nth_digit(_) }.map(19977..20001)
  13. __END__
  14. [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7]
  15. [1, 5, 2, 7, 2, 5, 2, 7, 3, 5, 2, 7, 4, 5, 2, 7, 5, 5, 2, 7, 6, 5, 2, 7, 7]