mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-22 00:23:47 +01:00
32 lines
492 B
Ruby
32 lines
492 B
Ruby
def get_power_and_remainder(n, p)
|
|
q = 0
|
|
while n % p == 0 do
|
|
n /= p
|
|
q += 1
|
|
end
|
|
|
|
[n, q]
|
|
end
|
|
|
|
def format_prime_factor(p, q)
|
|
case q
|
|
when 0
|
|
""
|
|
when 1
|
|
"(" + p.to_s + ")"
|
|
else
|
|
"(" + p.to_s + "**" + q.to_s + ")"
|
|
end
|
|
end
|
|
|
|
def prime_factors(n)
|
|
result = (2..Math.sqrt(n) + 1).reduce("") { |factors, p|
|
|
n, q = get_power_and_remainder(n, p)
|
|
factors + format_prime_factor(p, q)
|
|
}
|
|
|
|
if n > 1 then
|
|
result += format_prime_factor(n, 1)
|
|
end
|
|
result
|
|
end
|