smallest_number_with_at_least_n_divisors.pl 948 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 15 May 2021
  4. # https://github.com/trizen
  5. # Generate the smallest number that has at least n divisors.
  6. # See also:
  7. # https://oeis.org/A061799 -- Smallest number with at least n divisors.
  8. use 5.020;
  9. use warnings;
  10. use experimental qw(signatures);
  11. use ntheory qw(nth_prime);
  12. use Math::AnyNum qw(:overload);
  13. sub smallest_number_with_at_least_n_divisors ($threshold, $least_solution = Inf, $k = 1, $max_a = Inf, $sigma0 = 1, $n = 1) {
  14. if ($sigma0 >= $threshold) {
  15. return $n;
  16. }
  17. my $p = nth_prime($k);
  18. for (my $a = 1 ; $a <= $max_a ; ++$a) {
  19. $n *= $p;
  20. last if ($n > $least_solution);
  21. $least_solution = __SUB__->($threshold, $least_solution, $k + 1, $a, $sigma0 * ($a + 1), $n);
  22. }
  23. return $least_solution;
  24. }
  25. say smallest_number_with_at_least_n_divisors(60); #=> 5040
  26. say smallest_number_with_at_least_n_divisors(1000); #=> 245044800