almost_primes_in_range.jl 994 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/julia
  2. # Generate 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 almost_primes_in_range(A, B, n::Int64)
  8. A = max(A, (BIG ? big"2" : 2)^n)
  9. F = function(m, lo::Int64, j::Int64)
  10. lst = []
  11. hi = round(Int64, fld(B, m)^(1/j))
  12. if (lo > hi)
  13. return lst
  14. end
  15. if (j == 1)
  16. lo = round(Int64, max(lo, cld(A, m)))
  17. if (lo > hi)
  18. return lst
  19. end
  20. for q in (primes(lo, hi))
  21. push!(lst, m*q)
  22. end
  23. else
  24. for q in (primes(lo, hi))
  25. lst = vcat(lst, F(m*q, q, j-1))
  26. end
  27. end
  28. return lst
  29. end
  30. return sort(F((BIG ? big"1" : 1), 2, n))
  31. end
  32. # Generate 5-almost in the range [300, 1000]
  33. k = 5
  34. from = 300
  35. upto = 1000
  36. println(almost_primes_in_range(from, upto, k))