smallest_k-gonal_inverse_brute_force.pl 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/perl
  2. # Given an integer `n`, find the smallest integer k>=3 such that `n` is a k-gonal number.
  3. # Example:
  4. # a(12) = 5 since 12 is a pentagonal number, but not a square or triangular.
  5. # Based on code by Chai Wah Wu.
  6. # See also:
  7. # https://oeis.org/A176774
  8. use 5.020;
  9. use strict;
  10. use warnings;
  11. use experimental qw(signatures);
  12. use Math::AnyNum qw(:overload isqrt divmod ipolygonal_root polygonal);
  13. sub polygonal_inverse ($n) {
  14. for (my $k = (isqrt(8 * $n + 1) - 1) >> 1 ; $k >= 2 ; --$k) {
  15. my ($x, $y) = divmod(
  16. 2 * ($k * ($k - 2) + $n),
  17. $k * ($k - 1)
  18. );
  19. return $x if $y == 0;
  20. }
  21. }
  22. foreach my $i (1 .. 31) {
  23. my $n = 2**$i + 1;
  24. my $k = polygonal_inverse($n);
  25. my $d = ipolygonal_root($n, $k);
  26. say "2^$i + 1 = P($d, $k)";
  27. die 'error' if $n != polygonal($d, $k);
  28. }
  29. __END__
  30. 2^1 + 1 = P(2, 3)
  31. 2^2 + 1 = P(2, 5)
  32. 2^3 + 1 = P(3, 4)
  33. 2^4 + 1 = P(2, 17)
  34. 2^5 + 1 = P(3, 12)
  35. 2^6 + 1 = P(5, 8)
  36. 2^7 + 1 = P(3, 44)
  37. 2^8 + 1 = P(2, 257)
  38. 2^9 + 1 = P(9, 16)
  39. 2^10 + 1 = P(5, 104)
  40. 2^11 + 1 = P(3, 684)
  41. 2^12 + 1 = P(17, 32)
  42. 2^13 + 1 = P(3, 2732)
  43. 2^14 + 1 = P(5, 1640)
  44. 2^15 + 1 = P(33, 64)
  45. 2^16 + 1 = P(2, 65537)
  46. 2^17 + 1 = P(3, 43692)
  47. 2^18 + 1 = P(65, 128)
  48. 2^19 + 1 = P(3, 174764)
  49. 2^20 + 1 = P(17, 7712)
  50. 2^21 + 1 = P(129, 256)
  51. 2^22 + 1 = P(5, 419432)
  52. 2^23 + 1 = P(3, 2796204)
  53. 2^24 + 1 = P(257, 512)
  54. 2^25 + 1 = P(33, 63552)
  55. 2^26 + 1 = P(5, 6710888)
  56. 2^27 + 1 = P(513, 1024)
  57. 2^28 + 1 = P(17, 1973792)
  58. 2^29 + 1 = P(3, 178956972)
  59. 2^30 + 1 = P(1025, 2048)
  60. 2^31 + 1 = P(3, 715827884)