約数を求める(Ruby)

prime ライブラリを使う。結果は順不同。

require "prime"

def divisors(n)
  result = []
  
  doit = ->(pd, acc) {
    return if pd.empty?
    x, *xs = pd
    (0..x[1]).each do |i|
      e = acc * x[0] ** i
      result << e
      doit.(xs, e)
    end
  }
  doit.(n.prime_division, 1)
  
  result.uniq
end

p divisors(24)    #=>[1, 3, 2, 6, 4, 12, 8, 24]