Project Euler Problem #40

May 19, 2010

Read the details of the problem here


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


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)

def i = 1
while (sb.length() <= LIMIT) {

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.


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


Leave a Reply

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

You are commenting using your 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: