Project Euler Problem #40

May 19, 2010

Read the details of the problem here

Summary

Finding the nth digit of the fractional part of the irrational number.

Solution

No need for clever maths for this solution. Just create the string as described and pull the characters out as necessary.

def LIMIT = 1000000
def sb = new StringBuilder(LIMIT+10)
sb.append(".")

def i = 1
while (sb.length() <= LIMIT) {
  sb.append(i.toString())
  i++
}

i = 1
def answer = 1
while (i <= LIMIT) {
  answer *= sb[i].toInteger()
  i *= 10
}

This runs in 0.17 seconds. Being able to explicitly use a StringBuilder means that I can make this reasonably performant with losing the simple string-based approach to the solution. A Java version takes just 11 ms.

Conclusion

This is where Groovy’s easy explicit access to Java libraries can make a killer combination.

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: