It took me a fair bit of refactoring after I got the last test passing (generate 10 ) to get it this tight, but I like it.
def generate(n)
return [] if n == 1
factor = (2..n).find {|x| n % x == 0}
[factor] + generate(n / factor)
end
« svn replacement for git stash | Main | My New MVC Metaphor: The Command Line »
TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00e54fb013da88340128759f141d970c
Listed below are links to weblogs that reference Kata:Ruby:Prime Factors:
» Kata:Ruby:Tail Recursive Prime Factors from Radyology
At the request of a former employer here's a tail recursive version of the prime factors kata in Ruby. def generate(n, factors=[]) return factors if n == 1 new_factor = (2..n).find {|f| n % f == 0} generate(n / new_factor,... [Read More]
You can follow this conversation by subscribing to the comment feed for this post.
The comments to this entry are closed.
Nice. Stuff like this makes me continue believe in programming.
Posted by: Fredrik Rubensson | November 27, 2009 at 08:48 AM
Can you make this tail recursive
Posted by: unclebob | December 05, 2009 at 09:48 AM
Sure can:
http://www.benrady.com/2009/12/katarubytail-recursive-prime-factors.html
Posted by: Ben Rady | December 05, 2009 at 02:50 PM
This is really amazing. After staring this code for few minutes, I realized that the trick here is the fact that any number can be expressed as factors of only prime numbers and nothing else.
Posted by: Srikanth P Shreenivas | October 04, 2010 at 04:15 AM