110 Diophantine reciprocals II.pl 823 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 15 May 2021
  4. # https://github.com/trizen
  5. # Diophantine reciprocals II
  6. # https://projecteuler.net/problem=110
  7. # See also:
  8. # https://oeis.org/A018892
  9. # Runtime: 0.550s
  10. use 5.020;
  11. use warnings;
  12. use experimental qw(signatures);
  13. use ntheory qw(nth_prime);
  14. use Math::AnyNum qw(:overload);
  15. sub solve ($threshold, $least_solution = Inf, $k = 1, $max_a = Inf, $solutions = 1, $n = 1) {
  16. if ($solutions > $threshold) {
  17. return $n;
  18. }
  19. my $p = nth_prime($k);
  20. for (my $a = 1 ; $a <= $max_a ; ++$a) {
  21. $n *= $p;
  22. last if ($n > $least_solution);
  23. $least_solution = __SUB__->($threshold, $least_solution, $k + 1, $a, $solutions * (2 * $a + 1), $n);
  24. }
  25. return $least_solution;
  26. }
  27. my $LIMIT = 4 * 10**6;
  28. say solve(2 * $LIMIT + 1);