squarefree_almost_primes_in_range.jl 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/julia
  2. # Generate squarefree k-almost primes in range [A,B].
  3. # See also:
  4. # https://en.wikipedia.org/wiki/Almost_prime
  5. using Primes
  6. const BIG = false # true to use big integers
  7. function big_prod(arr)
  8. BIG || return prod(arr)
  9. r = big"1"
  10. for n in (arr)
  11. r *= n
  12. end
  13. return r
  14. end
  15. function squarefree_almost_primes_in_range(A, B, n::Int64)
  16. A = max(A, big_prod(primes(prime(n))))
  17. F = function(m, lo::Int64, j::Int64)
  18. lst = []
  19. hi = round(Int64, fld(B, m)^(1/j))
  20. if (lo > hi)
  21. return lst
  22. end
  23. if (j == 1)
  24. lo = round(Int64, max(lo, cld(A, m)))
  25. if (lo > hi)
  26. return lst
  27. end
  28. for q in (primes(lo, hi))
  29. push!(lst, m*q)
  30. end
  31. else
  32. for q in (primes(lo, hi))
  33. lst = vcat(lst, F(m*q, q+1, j-1))
  34. end
  35. end
  36. return lst
  37. end
  38. return sort(F((BIG ? big"1" : 1),2,n))
  39. end
  40. # Generate squarefree 5-almost in the range [3000, 10000]
  41. k = 5
  42. from = 3000
  43. upto = 10000
  44. println(squarefree_almost_primes_in_range(from, upto, k))