Created
July 30, 2013 12:42
-
-
Save ackintosh/6112564 to your computer and use it in GitHub Desktop.
The prime factors.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Fixnum | |
def prime? | |
return false if self <= 1 | |
(2..(Math::sqrt(self))).each do |n| | |
return false if self % n == 0 | |
end | |
true | |
end | |
def prime_factors | |
result = [] | |
p = 2 | |
n = self | |
begin | |
if !p.prime? | |
p += 1 | |
next | |
end | |
quot, rem = n.divmod(p) | |
if rem == 0 | |
result << p | |
n = quot | |
p = 2 | |
else | |
p += 1 | |
end | |
end while !(quot == 1 && rem == 0) | |
result | |
end | |
end | |
p 13195.prime_factors | |
# [5, 7, 13, 29] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment