Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created July 30, 2013 12:42
Show Gist options
  • Save ackintosh/6112564 to your computer and use it in GitHub Desktop.
Save ackintosh/6112564 to your computer and use it in GitHub Desktop.
The prime factors.
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