521 Smallest prime factor.pl 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 14 March 2020
  4. # https://github.com/trizen
  5. # Smallest prime factor
  6. # https://projecteuler.net/problem=521
  7. # For each prime p < sqrt(n), we count how many integers k <= n have lpf(k) = p.
  8. # We have G(n,p) = number of integers k <= n such that lpf(k) = p.
  9. # G(n,p) can be evaluated recursively over primes q < p.
  10. # There are t = floor(n/p) integers <= n that are divisible by p.
  11. # From t we subtract the number integers that are divisible by smaller primes than p.
  12. # The sum of the primes is p * G(n,p).
  13. # When G(n,p) = 1, then G(n,p+r) = 1 for all r >= 1.
  14. # Runtime: 6 min, 24 sec
  15. use 5.020;
  16. use integer;
  17. use ntheory qw(:all);
  18. use experimental qw(signatures);
  19. my %cache;
  20. my $MOD = 1e9;
  21. sub G ($n, $p) {
  22. if ($p > sqrt($n)) {
  23. return 1;
  24. }
  25. if ($p == 2) {
  26. return ($n >> 1);
  27. }
  28. if ($p == 3) {
  29. my $t = $n / 3;
  30. return ($t - ($t >> 1));
  31. }
  32. my $key = "$n $p";
  33. if (exists $cache{$key}) {
  34. return $cache{$key};
  35. }
  36. my $u = 0;
  37. my $t = $n / $p;
  38. for (my $q = 2 ; $q < $p ; $q = next_prime($q)) {
  39. my $v = __SUB__->($t - ($t % $q), $q);
  40. if ($v == 1) {
  41. $u += prime_count($q, $p - 1);
  42. last;
  43. }
  44. else {
  45. $u += $v;
  46. }
  47. }
  48. if ($n < 1e7) {
  49. $cache{$key} = $t - $u;
  50. }
  51. $t - $u;
  52. }
  53. sub S($n) {
  54. my $sum = 0;
  55. my $s = sqrtint($n);
  56. forprimes {
  57. $sum += mulmod($_, G($n, $_), $MOD);
  58. } $s;
  59. addmod($sum, sum_primes(next_prime($s), $n) % $MOD, $MOD);
  60. }
  61. say S(1e12);
  62. __END__
  63. S(10^1) = 28
  64. S(10^2) = 1257
  65. S(10^3) = 79189
  66. S(10^4) = 5786451
  67. S(10^5) = 455298741
  68. S(10^6) = 37568404989
  69. S(10^7) = 3203714961609
  70. S(10^8) = 279218813374515
  71. S(10^9) = 24739731010688477
  72. S(10^10) = 2220827932427240957
  73. S(10^11) = 201467219561892846337