Project Euler Problem #99

November 18, 2009

Read the details of the problem here

Summary

Which base/exponent pair in the file has the greatest numerical value?

Solution

I took the straightforward approach to this one. As the resulting numbers would be huge it was just a matter of using log10(base) * exp and comparing those values. The coded solution is trivial.

def ( i, answer, max ) = [ 1, -1, 0.0 ]

new File("base_exp.txt").eachLine {
    def ( base, exp ) = it.split(",")*.toDouble()
    def log = Math.log10(base) * exp
    if (log > max) ( answer, max ) = [ i, log ]
    i++ 
}

It ran in 46 ms and took a very short time to write!

Conclusion

Groovy was a very nice language to use for this. It was very easy to read the file and process the contents. See how the spread-dot operator is used on the list resulting from the split to convert both operands in to Doubles ready for the next step. The only slightly irritating part was that I had to maintain my own record count as there is no eachWithIndex() method available on a File object. I could have treated this differently by reading into a list first but this seemed quicker!

As there was no heavy maths processing performance was fine, it was quick to write and the code intent is clear.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: