Finding all factors of an integer

I found this question but it didn’t quite answer mine.

I want to list all the factors of a number, n. I found Primes.factor(n) which returns all the primes with their powers. And I found Iterators.product which could, in principle, give all the factors.

In Python, there’s an * operator that breaks out a list into separate inputs.

I created an array like this:

a = []
for p in Primes.factor(n)
    append!(a,[0:p[2])
end

Then I wanted to iterate over all combinations of these powers:

for x in Iterators.product(*a)
    #Do stuff with x being an array or tuple or list or whatever of powers
end

But I guess * is a python thing! Anyway, general hints, tips, and good ideas for how to do this in Julia?

I’m not sure I understand your question correcty, but I think you’re looking for splatting:

Iterators.product(a...)

for example:

julia> a = [0:1, 0:2]
2-element Array{UnitRange{Int64},1}:
 0:1
 0:2

julia> collect(Iterators.product(a...))
2×3 Array{Tuple{Int64,Int64},2}:
 (0, 0)  (0, 1)  (0, 2)
 (1, 0)  (1, 1)  (1, 2)
5 Likes

I’m not sure why you’re using the collect? But the splat seems to do exactly what I was looking for. Thank you for your help.

Sorry the collect was just to show what’s in the iterator, clearly you don’t have to materialise for your use case!

1 Like

you might also be interrested in these methods for factor:

julia> factor(Set, 12)
Set{Int64} with 2 elements:
  2
  3

julia> factor(Vector, 12)
3-element Array{Int64,1}:
 2
 2
 3

julia> factor(Dict, 12)
Dict{Int64,Int64} with 2 entries:
  2 => 2
  3 => 1
3 Likes