820 N-th digit of Reciprocals.pl 551 B

1234567891011121314151617181920212223242526272829303132333435
  1. #!/usr/bin/perl
  2. # N-th digit of reciprocals
  3. # https://projecteuler.net/problem=820
  4. # Naive approach.
  5. use 5.020;
  6. use warnings;
  7. use ntheory qw(:all);
  8. use experimental qw(signatures);
  9. use Math::GMPz;
  10. sub S ($n) {
  11. my $m = Math::GMPz::Rmpz_init();
  12. my $t = Math::GMPz::Rmpz_init();
  13. Math::GMPz::Rmpz_ui_pow_ui($m, 10, $n);
  14. my $sum = 0;
  15. foreach my $k (1 .. $n) {
  16. Math::GMPz::Rmpz_tdiv_q_ui($t, $m, $k);
  17. $sum += Math::GMPz::Rmpz_mod_ui($t, $t, 10);
  18. }
  19. return $sum;
  20. }
  21. say S(7);
  22. say S(100);
  23. say S(1e7);