Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e9bf20a

Browse files
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

‎README.md‎

Lines changed: 1 addition & 0 deletions
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

‎exercism/prime_factors.rb‎

Lines changed: 28 additions & 0 deletions
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)

AltStyle によって変換されたページ (->オリジナル) /