521 Smallest prime factor.sf 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 20 July 2020
  4. # https://github.com/trizen
  5. # Smallest prime factor
  6. # https://projecteuler.net/problem=521
  7. # Algorithm with sublinear time for computing:
  8. #
  9. # Sum_{k=2..n} lpf(k)
  10. #
  11. # where:
  12. # lpf(k) = the least prime factor of k
  13. # For each prime p < sqrt(n), we count how many integers k <= n have lpf(k) = p.
  14. # We have G(n,p) = number of integers k <= n such that lpf(k) = p.
  15. # G(n,p) can be evaluated recursively over primes q < p.
  16. # Equivalently, G(n,p) is the number of p-rough numbers <= floor(n/p);
  17. # There are t = floor(n/p) integers <= n that are divisible by p.
  18. # From t we subtract the number integers that are divisible by smaller primes than p.
  19. # The sum of the primes is p * G(n,p).
  20. # When G(n,p) = 1, then G(n,p+r) = 1 for all r >= 1.
  21. # Runtime: 3.742s (when Kim Walisch's `primesum` tool is installed).
  22. local Num!USE_PRIMESUM = true
  23. local Num!USE_PRIMECOUNT = false
  24. func S(n) {
  25. var t = 0
  26. var s = n.isqrt
  27. s.each_prime {|p|
  28. t += p*p.rough_count(idiv(n,p))
  29. }
  30. t + sum_primes(s.next_prime, n)
  31. }
  32. say (S(1e12) % 1e9)
  33. __END__
  34. S(10^1) = 28
  35. S(10^2) = 1257
  36. S(10^3) = 79189
  37. S(10^4) = 5786451
  38. S(10^5) = 455298741
  39. S(10^6) = 37568404989
  40. S(10^7) = 3203714961609
  41. S(10^8) = 279218813374515
  42. S(10^9) = 24739731010688477
  43. S(10^10) = 2220827932427240957
  44. S(10^11) = 201467219561892846337