Project Euler 20

Problem 20

  • BigInteger を使う方法と、使わない方法の 2 通りで解いてみた。
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Linq;

class PE020 {
    // BigInteger を使う方法
    static int Calc1() {
        BigInteger x = 1;
        for (int i = 2; i <= 100; i++) {
            x *= i;
        }

        int ans = 0;
        foreach (char c in x.ToString()) {
            ans += c - '0';
        }
        return ans;;
    }

    // BigInteger と Linq を使う方法
    static int Calc2() {
        return Enumerable.Range(1, 100)
                 .Aggregate(new BigInteger(1), (x, y) => x * y)
                 .ToString()
                 .Select(x => x - '0')
                 .Sum();
    }

    static List<int> Mul(List<int> a, int b) {
        var ret = new List<int>();
        int carry = 0;
        foreach (int x in a) {
            int y = x * b + carry;
            ret.Add(y % 10);
            carry = y / 10;
        }

        while (carry > 0) {
            ret.Add(carry % 10);
            carry /= 10;
        }
        return ret;
    }

    // BigIntegerを使わない方法
    static int Calc3() {
        return Enumerable.Range(1, 100)
                 .Aggregate(new List<int>() { 1 }, (x, y) => Mul(x, y))
                 .Sum();
    }

    static void Main() {
        Console.WriteLine(Calc1());
        Console.WriteLine(Calc2());
        Console.WriteLine(Calc3());
    }
}