## Kata:Ruby:Prime Factors

##### November 13, 2009

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
```

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:

https://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