legendre_prime_counting_function_from_k-rough_count.sf 808 B

123456789101112131415161718192021222324252627282930
  1. #!/usr/bin/ruby
  2. # The Legendre prime counting function, defined in terms of the k-rough counting function.
  3. # Using the Legendre phi function, π(n), can be defined as:
  4. # π(n) = 0 when n < 2
  5. # π(n) = φ(n, a) + a - 1, where a = π(√n), n ≥ 2
  6. # See also:
  7. # https://rosettacode.org/wiki/Legendre_prime_counting_function
  8. func legendre_phi(n, a) {
  9. prime(a+1).rough_count(n)
  10. }
  11. func legendre_prime_count(n) is cached {
  12. return 0 if (n < 2)
  13. var a = __FUNC__(n.isqrt)
  14. legendre_phi(n, a) + a - 1
  15. }
  16. print("e n Legendre builtin\n",
  17. "- - -------- -------\n")
  18. for n in (1 .. 9) {
  19. printf("%d %12d %10d %10d\n", n, 10**n,
  20. legendre_prime_count(10**n), prime_count(10**n))
  21. assert_eq(legendre_prime_count(10**n), prime_count(10**n))
  22. }