Project Euler Problem #20

February 8, 2010

Read the details of the problem here

Summary

Find the sum of digits in 100!

Solution

Really straightforward if you’ve got BigInteger support.

def answer =
    ((2..100).inject(1G) { p, n -> p * n })
        .toString().toList()*.toInteger().sum()

Runs in 0.48 seconds. Using BigInteger.ONE (in Groovy – 1G) as the seed to inject(){} seems like the cleanest way of forcing type that I’ve found for problems like this.

Conclusion

Groovy made this a simple one liner (though I’ve split it for readability).

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: