Duncan's blog

January 26, 2009

Project Euler: problem 20

Filed under: Project Euler,Python — duncan @ 12:00 am
Tags: , ,

Problem 20:

n! means n x (n − 1) x … x 3 x 2 x 1

Find the sum of the digits in the number 100!

Another one that had previously foxed me in CFML (on Coldfusion 5), but was simple in Python:

limit = 100
total = 0
product = 1

for i in range(limit, 1, -1):
        product = product * i

prodStr = repr(product)
length = len(prodStr)

for i in range(length):
        total = total + int(prodStr[i])

print(total)

Similar code to problem 16. I work out 100!, then I turn the number into a string, work out the length of the string, loop through the string, adding up each digit.

This is only my second bit of Python ever, so I’d love some feedback from anyone with more experience of the language.

1 Comment »

  1. […] previously blogged about this Project Euler puzzle nearly 5 years ago, using Python.  This is my approach using PHP as a simple practical exercise for myself, and I’d […]

    Pingback by Project Euler: problem 20 (PHP) | Duncan's blog — October 3, 2014 @ 8:02 am | Reply


RSS feed for comments on this post. TrackBack URI

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

Create a free website or blog at WordPress.com.

%d bloggers like this: