B2 – Project Euler #20

This is a programming exercise. You must write a Python script that solves Project Euler Problem #20. If you do not want to sign up for Project Euler, you may ask the instructor for the correct answer.

Requirements

Project Euler Problem #20 reads as follows:

Find the sum of the digits in the number 100!

Create a Python script named euler20.py that prints the answer to the above question to the console. You must use variables and at least one loop.

Background

The factorial of a number n is defined as follows:

n! = n × (n – 1) × (n – 2) × ... × 3 × 2 × 1

You can calculate the factorial of a number in Python using the math.factorial() function. For example:

import math
print math.factorial(10)

Example

The factorial of 10 is:

10! = 10 × 9 × 8 × 7 × 6 × 5 × 3 × 2 × 1
    = 
3628800

The sum of the digits in the number 10! is:

3 + 6 + 2 + 8 + 8 + 0 + 0 = 27

Double check your program using the answer provided above, then solve for the case where n = 100.

Hints

There are two hints that will help significantly with this problem. I recommend you break this into two subproblems: (a) how to get the last digit in a number, and (b) how to strip the last digit off a number.

First, notice what happens when you take a number modulo 10:

print 123 % 10  # Prints 3
print 12 % 10   # Prints 2

Now, notice what happens when you use integer division (using the double slash // operator):

print 123 // 10  # Prints 12
print 12 // 10   # Prints 1
print 1 // 10    # Prints 0

Combine both of these properly in a loop and you'll get your answer!

Submission

When complete, show your script to the instructor for credit. If you do not finish by the end of the class, you may email the script to the instructor. Please include the following subject line for your email:

MSAN 501 Day 1 – Euler #20

Make sure you include your full name in the email body.