601 Divisibility streaks.pl 908 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 30 April 2017
  5. # https://github.com/trizen
  6. # https://projecteuler.net/problem=601
  7. # Runtime: 0.028s
  8. =for comment
  9. The numbers n in the range [1..31] with non-zero values for P(n, 4^n), are:
  10. [1, 2, 3, 4, 6, 7, 8, 10, 12, 15, 16, 18, 22, 24, 26, 28, 30, 31]
  11. All this numbers satisfy the following inequality:
  12. lcm(1..n) != lcm(1..(n+1)).
  13. For this numbers, P(n, 4^n) can be efficiently computed as follows:
  14. a = floor((4^n - 2) / lcm(1..n))
  15. b = lcm(1..(n+1)) / lcm(1..n)
  16. P(n, 4^n) = a - floor(a/b)
  17. =cut
  18. use 5.010;
  19. use strict;
  20. use ntheory qw(lcm);
  21. sub count {
  22. my ($n, $k) = @_;
  23. my $lcm = lcm(1 .. $n);
  24. my $period = lcm($lcm, $n + 1) / $lcm;
  25. my $count = int(($k - 2) / $lcm);
  26. $count - int($count / $period);
  27. }
  28. my $sum = 0;
  29. foreach my $n (1 .. 31) {
  30. $sum += count($n, 4**$n);
  31. }
  32. say $sum;