【ProjectEuler】ProjectEuler_020

using System;
using System.Collections.Generic;
using System.Text;

namespace projecteuler020
{
    class Program
    {
        static void Main(string[] args)
        {
            F1();
        }

        private static void F1()
        {
            Console.WriteLine(new System.Diagnostics.StackTrace().GetFrame(0).GetMethod());
            DateTime timeStart = DateTime.Now;

            string result = "1";
            int maxValue = 100;
            int sum = 0;

            for (int i = 1; i <= maxValue; i++)
            {
                result = longMulti(result, i);
            }

            for (int i = result.Length - 1; i >= 0; i--)
            {
                sum += result[i] - '0';
            }

            Console.WriteLine("100! = " + result);
            Console.WriteLine("The sum of these digits is " + sum);

            Console.WriteLine("Total Milliseconds is " + DateTime.Now.Subtract(timeStart).TotalMilliseconds + "\n\n");
        }

        private static string longMulti(string s1, int n)
        {
            string result = "0";
            for (int i = 0; i < n; i++)
            {
                result = longAdd(result, s1, 0);
            }
            return result;
        }


        /// <summary>
        /// 超大数字表达式加法
        /// </summary>
        /// <param name="s1">数1</param>
        /// <param name="s2">数2</param>
        /// <param name="c">后面的数的进位,范围0~2</param>
        /// <returns></returns>
        private static string longAdd(string s1, string s2, int c)
        {
            //s1,s2的末位Index
            int l1 = s1.Length - 1;
            int l2 = s2.Length - 1;
            int x;

            //如果2个数都不为空
            if (l1 >= 0 && l2 >= 0)
            {
                x = s1[l1] - '0' + s2[l2] - '0' + c;
                return longAdd(s1.Substring(0, l1), s2.Substring(0, l2), x / 10) + (x % 10).ToString();
            }


            //下面的情况,s1和s2中至少有一个为空,我们要做的是找到那个不为空的进行下一步操作
            //把不为空的值放到s1里
            if (l2 >= 0)
            {
                s1 = s2;
                l1 = l2;
            }
            else if (l1 == -1)   //表示全为空,判断最后的进位,如果没进位,返回空白,结束递归
            {
                if (c != 0)
                {
                    return c.ToString();
                }
                return "";
            }

            x = s1[l1] - '0' + c;

            //如果s1只有1位
            if (l1 == 0)
            {
                return x.ToString();
            }

            //如果s1有不止一位
            return longAdd(s1.Substring(0, l1), "", x / 10) + (x % 10).ToString();
        }

    }
}

/*
Void F1()
100! = 9332621544394415268169923885626670049071596826438162146859296389521759999
32299156089414639761565182862536979208272237582511852109168640000000000000000000
00000
The sum of these digits is 648
Total Milliseconds is 436.5554
*/

你可能感兴趣的:(c,String,Class)