ArticleS. UncleBob.
ThePrimeFactorsKata [add child]

The Prime Factors Kata



Here is a kata for the Prime Factors problem.

This is a very short Kata. The final algorithm is three lines of code. Interestingly enough there are 40 lines of test code.

Although quite short, this kata is fascinating in the way it shows how ‘if’ statements become ‘while’ statements as the number of test cases increase. It’s also a wonderful example of how algorithms sometimes become simpler as they become more general.

I stumbled upon this little kata one evening when my son was in 7th grade. He had just discovered that all numbers can be broken down into a product of primes and was interested in exploring this further. So I wrote a little ruby program, test-first, and was stunned by how the algorithm evolved.

I have done this particular kata in Java 5.0. This should give you a feel for the power and convenience of some of the new features.




!commentForm
 Sun, 26 Jun 2005 19:57:16, KelleyHarris[?], Great learning aid. More comments welcome on the slides.
Great learning aid and exercise. For rev 2, consider adding your thoughts via notes on some of the slides. Especially the exloration on slides 29-34. (seventh test) I also wondered why tests for inputs of 5 & 7 were not done, and generally a criteria for when to stop adding tests. This generalized in my mind, to wanting to hear/learn the reasoning of the masters, as well as the actions.

I'd be interested in hearing your thoughts about the pros & cons of the nested for loops versus the earlier version with nested while loops. The for loops are certainly more compact, but, so far, I found myself mentally translating the for loops into while loops when rereading the final version. It wasn't obvious to me which form would be more clear for later readers.

Note that negative integer inputs would fail. In rev 2, consider adding a note about negative numbers in the requirements.


(FYI, used Eclipse 3.1RC4 and Java 5.0.)


 Thu, 15 Sep 2005 06:12:38, Masa, aaa
 Tue, 4 Apr 2006 17:23:49, David Carlton, Unnecessary if clause.
I just went through this with a coworker; interesting!

One thing that seemed fishy to us: on slide 21, you have two "if (n > 1)" guards. The outer one is unnecessary; we didn't introduce that guard when doing our own implementation, and in fact didn't even notice that our implementation had diverged from yours until several slides later. So we didn't think that having two if guards was natural.

This is, I think, an important difference: on slide 33, you turn that "if" into a "while" (while adding the "candidate++"), which is where the final green bar occurs. Whereas in our version, you have to add the "while" and the "candidate++" at the same time, making the final green bar transition slightly more of a leap than in your version.

I also agree with the previous comment that the nested for loops, while shorter than the while loops, aren't necessarily clearer.