207 Integer partition equations.pl 992 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # Date: 24 August 2016
  4. # License: GPLv3
  5. # Website: https://github.com/trizen
  6. # https://projecteuler.net/problem=207
  7. # Runtime: 34.802s
  8. use 5.010;
  9. use strict;
  10. use warnings;
  11. my %table;
  12. sub pp_ratio {
  13. my ($n) = @_;
  14. my $perfect = 0;
  15. my $non_perfect = 0;
  16. for (my $i = 1 ; ; ++$i) {
  17. my $k = $i * ($i + 1);
  18. last if $k > $n;
  19. exists($table{$k}) ? ++$perfect : ++$non_perfect;
  20. }
  21. $perfect / ($perfect + $non_perfect);
  22. }
  23. my $ratio = 1 / 12345;
  24. foreach my $i (1 .. 30) {
  25. undef $table{4**$i - 2**$i};
  26. }
  27. my $k = 1;
  28. my $j = 2;
  29. my $upper_bound;
  30. for (my $i = 1 ; ; $i += $k) {
  31. if (pp_ratio($i * ($i + 1)) < $ratio) {
  32. $upper_bound = $i * ($i + 1);
  33. last;
  34. }
  35. if ($i % $j == 0) {
  36. ++$k;
  37. ++$j;
  38. }
  39. }
  40. for (my $i = int sqrt($upper_bound) - 2 * $k ; ; ++$i) {
  41. if (pp_ratio($i * ($i + 1)) < $ratio) {
  42. say $i * ($i + 1);
  43. last;
  44. }
  45. }