count_of_cube-full_numbers.sf 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/ruby
  2. # Fast algorithm for counting the number of cube-full numbers <= n.
  3. # A positive integer n is considered cube-full, if for every prime p that divides n, so does p^3.
  4. # See also:
  5. # THE DISTRIBUTION OF CUBE-FULL NUMBERS, by P. SHIU (1990).
  6. # OEIS:
  7. # https://oeis.org/A036966 -- 3-full (or cube-full, or cubefull) numbers: if a prime p divides n then so does p^3.
  8. func cubefull_count(n) {
  9. var total = 0
  10. for a in (1 .. n.iroot(5)) {
  11. for b in (1 .. iroot(floor(n / a**5), 4)) {
  12. var t = (a**5 * b**4)
  13. total += (iroot(floor(n/t), 3) * moebius(a*b)**2)
  14. }
  15. }
  16. return total
  17. }
  18. func sum_of_cubefull_divisors_count(n) {
  19. # Let:
  20. # f(n) = 1 if n is cube-full; 0 otherwise
  21. # Then:
  22. # a(n) = Sum_{k=1..n} Sum_{d|k} f(d)
  23. # = Sum_{k=1..n} f(d) * floor(n/k)
  24. # Which can be computed in sublinear time as:
  25. # a(n) = Sum_{k=1..s} (f(k)*floor(n/k) + R(floor(n/k))) - s*R(s)
  26. # where:
  27. # s = floor(sqrt(n))
  28. # R(n) = Sum_{k=1..n} f(k)
  29. var s = n.isqrt
  30. var t = 0
  31. for k in (1..s) {
  32. t += floor(n/k) if k.is_powerful(3)
  33. t += cubefull_count(floor(n/k))
  34. }
  35. t -= s*cubefull_count(s)
  36. return t
  37. }
  38. say 50.of(cubefull_count)
  39. say 50.of(sum_of_cubefull_divisors_count)
  40. assert_eq(sum_of_cubefull_divisors_count(16), 19)
  41. assert_eq(sum_of_cubefull_divisors_count(100), 126)
  42. assert_eq(sum_of_cubefull_divisors_count(1e4), 13344)
  43. __END__
  44. [0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
  45. [0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 30, 32, 33, 34, 35, 36, 40, 41, 42, 43, 44, 45, 46, 47, 49, 50, 51, 52, 53, 54, 55, 56, 59, 60]