1_over_n_period_length.pl 775 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 09 October 2016
  5. # Website: https://github.com/trizen
  6. # The period length after the decimal point of 1/n.
  7. # This is defined only for integers prime to 10.
  8. # Inspired by N. J. Wildberger's video:
  9. # https://www.youtube.com/watch?v=lMrz7ISoDGs
  10. # See also:
  11. # https://oeis.org/A002329
  12. use 5.010;
  13. use strict;
  14. use warnings;
  15. use ntheory qw(divisors euler_phi powmod);
  16. sub period_length_1_over_n {
  17. my ($n) = @_;
  18. my @divisors = divisors(euler_phi($n));
  19. foreach my $d (@divisors) {
  20. if (powmod(10, $d, $n) == 1) {
  21. return $d;
  22. }
  23. }
  24. return -1;
  25. }
  26. foreach my $n (1 .. 99) {
  27. my $l = period_length_1_over_n($n);
  28. printf("P(%2d) = %d\n", $n, $l) if $l != -1;
  29. }