Friday, February 06, 2009

Project Euler - Problem 3

Problem 3 reads as follows:

"The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?"


This one is easy, thanks to Ruby's mathn library and the prime_division method. You can read more about it and even see the source code for the method at the documentation site.

All we have to do is require the mathn library, which comes with Ruby by default. I checked on my Windows and Mac OSX machines. Then call the prime_division method on the integer. That creates a multidimensional array.

For each item in the array, there are 2 numbers. The first is the actual prime number and the second relates how many times that prime number can be factored out. So, for the number 9, you would end up with [3,2].

Lastly, we grab the last prime number in the array for the answer.

require 'mathn'
primeArray = 600851475143.prime_division
puts primeArray[primeArray.length - 1][0]

Monday, February 02, 2009

Calling XSLT templates with predicates..

This is just a mental note for me, so hopefully I won't forget it in the future.

If you have an XSLT template that limits the result set with a predicate, you must call that template with the predicate intact. Here's an example:

Wrong:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="Items">
<xsl:apply-templates select="Item" />
</xsl:template>

<xsl:template match="Item[status='archived']">
<xsl:element name="title">
<xsl:value-of select="title" />
</xsl:element>
</xsl:template>

</xsl:stylesheet>


Right:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="Items">
<xsl:apply-templates select="Item[status='archived']" />
</xsl:template>

<xsl:template match="Item[status='archived']">
<xsl:element name="title">
<xsl:value-of select="title" />
</xsl:element>
</xsl:template>

</xsl:stylesheet>


I am ashamed at how long it took me to figure out what I was doing wrong. ;)