solve_congruence_equation_example.pl 544 B

123456789101112131415161718192021222324252627
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # Date: 24 August 2016
  4. # License: GPLv3
  5. # Website: https://github.com/trizen
  6. # An example for how to solve a linear congruence equation.
  7. # Solving for x in:
  8. # (10^5)x + 19541 = 0 (mod 19543)
  9. #
  10. # which is equivalent with:
  11. # (10^5)x = -19541 (mod 19543)
  12. use 5.010;
  13. use strict;
  14. use warnings;
  15. use ntheory qw(invmod);
  16. my $k = 10**5; # coefficient of x
  17. my $r = -19541; # congruent to this
  18. my $m = 19543; # modulo this number
  19. say "x = ", (invmod($k, $m) * $r) % $m;