mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-21 16:13:47 +01:00
5kyu: add primes in numbers
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
b4062b40c8
commit
29b9da0f5e
2 changed files with 33 additions and 0 deletions
32
5kyu/primes_in_numbers/solution.rb
Normal file
32
5kyu/primes_in_numbers/solution.rb
Normal file
|
@ -0,0 +1,32 @@
|
|||
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
|
|
@ -116,6 +116,7 @@
|
|||
### Ruby
|
||||
|
||||
- [Best travel](https://www.codewars.com/kata/55e7280b40e1c4a06d0000aa) - [solution](5kyu/best_travel)
|
||||
- [Primes in numbers](https://www.codewars.com/kata/54d512e62a5e54c96200019e) - [solution](5kyu/primes_in_numbers)
|
||||
|
||||
## 6 kyu
|
||||
|
||||
|
|
Loading…
Reference in a new issue