C# Implementation of Problem 20

View source code here on GitHub!

Problem Solution

class p0020
: Euler.IEuler
object Answer ()
 1/*
 2Project Euler Problem 20
 3
 4Problem:
 5
 6n! means n × (n − 1) × ... × 3 × 2 × 1
 7
 8For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
 9and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
10
11Find the sum of the digits in the number 100!
12*/
13using System;
14
15namespace Euler
16{
17    public class p0020 : IEuler
18    {
19        public object Answer()
20        {
21            ulong[] numbers = new ulong[10];
22            const ulong ten17 = 100000000000000000;
23            numbers[0] = 1;
24            for (byte i = 2; i <= 100; i++)
25            {
26                for (byte j = 0; j < 10; j++)
27                    numbers[j] *= i;
28                for (byte j = 0; j < 9; j++)
29                    if (numbers[j] > ten17)
30                    {
31                        numbers[j + 1] += numbers[j] / ten17;
32                        numbers[j] %= ten17;
33                    }
34            }
35            ulong answer = 0;
36            ulong power = 1;
37            for (byte i = 0; i < 19; i++)
38            {
39                for (byte j = 0; j < 10; j++)
40                {
41                    ulong value = numbers[j] / power;
42                    answer += value % 10;
43                }
44                power *= 10;
45            }
46            return (short)answer;
47        }
48    }
49}

Tags: large-numbers, digit-sum, factorial