Skip to content

Commit e9bf20a

Browse files
committed
exercism 81 prime_factors
1 parent 567453b commit e9bf20a

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,7 @@ solution of many challenges of [Leetcode](https://leetcode.com/), [Exercism](htt
306306
78. [Binary Search Tree](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/binary_search_tree.rb)
307307
79. [Rotational Cipher](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/rotational_cipher.rb)
308308
80. [Largest Series Product](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/largest_series_product.rb)
309+
81. [Prime Factors](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/prime_factors.rb)
309310

310311
<a name="leetcode"/>
311312

Diff for: exercism/prime_factors.rb

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Problem: https://exercism.org/tracks/ruby/exercises/prime-factors
2+
3+
# Solution
4+
class PrimeFactors
5+
def self.of(n)
6+
return [] if n<2
7+
prime_factors = []
8+
factor = 2
9+
while n>1
10+
while n%factor ==0
11+
prime_factors<<factor
12+
n/=factor
13+
end
14+
factor+=1
15+
end
16+
prime_factors
17+
end
18+
end
19+
20+
# Solution (Recursive)
21+
class PrimeFactors
22+
def self.of(n)
23+
return [] if n < 2
24+
factor = (2..n).find { |i| n % i == 0 }
25+
[factor] + of(n / factor)
26+
end
27+
end
28+

0 commit comments

Comments
 (0)