smallest_number_with_n_divisors.pl 990 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  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 exactly n divisors.
  6. # See also:
  7. # https://oeis.org/A005179 -- Smallest number with exactly 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_n_divisors ($threshold, $least_solution = Inf, $k = 1, $max_a = Inf, $sigma0 = 1, $n = 1) {
  14. if ($sigma0 == $threshold) {
  15. return $n;
  16. }
  17. if ($sigma0 > $threshold) {
  18. return $least_solution;
  19. }
  20. my $p = nth_prime($k);
  21. for (my $a = 1 ; $a <= $max_a ; ++$a) {
  22. $n *= $p;
  23. last if ($n > $least_solution);
  24. $least_solution = __SUB__->($threshold, $least_solution, $k + 1, $a, $sigma0 * ($a + 1), $n);
  25. }
  26. return $least_solution;
  27. }
  28. say smallest_number_with_n_divisors(60); #=> 5040
  29. say smallest_number_with_n_divisors(1000); #=> 810810000