686 Powers of Two.pl 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 05 November 2019
  4. # https://github.com/trizen
  5. # The first few exponents are: 90, 379, 575, 864, 1060, 1545, 1741, 2030, 2226, 2515, 2711, 3000, 3196, 3681, 3877, 4166, 4362, 4651, 4847, 5136, ...
  6. # The set of differences between consecutive exponents is: {196, 289, 485}.
  7. # Can also be solved by using the denominators of semiconvergents of log_10(2).
  8. # https://projecteuler.net/problem=686
  9. # Runtime: 0.787s
  10. use 5.020;
  11. use experimental qw(signatures);
  12. my $ln2 = log(2);
  13. my $ln5 = log(5);
  14. my $ln10 = log(10);
  15. sub isok($n) {
  16. int(exp($ln2 * ($n - int(($n * $ln2) / $ln10) + 2) + $ln5 * (2 - int(($n * $ln2) / $ln10)))) == 123;
  17. }
  18. my $count = 1;
  19. my $k = do { my $n = 1; ++$n while (!isok($n)); $n };
  20. my $nth = 678910;
  21. while (1) {
  22. if (isok($k + 196)) {
  23. ++$count;
  24. $k += 196;
  25. }
  26. elsif (isok($k + 289)) {
  27. ++$count;
  28. $k += 289;
  29. }
  30. elsif (isok($k + 485)) {
  31. ++$count;
  32. $k += 485;
  33. }
  34. if ($count == $nth) {
  35. say "Final result: $k";
  36. last;
  37. }
  38. }