123456789四则运算

代码说明:在123456789或987654321中插入+-*/四则符号来算出一个固定的值。asc为true时是123456789,反之为987654321。

123456789算100,C#下时间为15秒,VBA下为56秒,快了3/4。

版权说明:本文来自狼版http://blog.csdn.net/northwolves/archive/2009/11/20/4841068.aspx一文,试着用C#实现了一下。初学C#,如果哪边有什么不对或可以优化,请大家指点。

 

    static void GetAllResult(int result, Boolean asc)
    {
        int temp=0,num=0;
        string[] x = new string[9];
        string[] op = new string[5]{"+","-","*","/",""};
        string outResult;
        StringBuilder sb = new StringBuilder();
        Stopwatch sw = new Stopwatch();
        sw.Start();
        Console.WriteLine("运算中,请稍候......");
        for (int i = 0; i <= Math.Pow(5,8); i++)
        {
            temp = i;
            x[0] = (asc ? 1 : 9).ToString();
            for (int j = 1; j <= 8; j++)
            {
                x[j] = op[temp % 5] + (asc?j + 1: 9 - j).ToString();
                temp=temp /5;
            }
            outResult = string.Join("",x);
            if ((new DataTable().Compute(outResult ,null)).ToString() == result.ToString())
            {
                num++;
                sb.Append("解 " + num + ":\t" + outResult + "=" + result + "\n");
            }
        }
        Console.WriteLine(sb.ToString());
        sw.Stop();
        Console.WriteLine(sw.Elapsed.ToString());
        Console.ReadLine();
    }
    static void Main(string[] args)
    {
        GetAllResult(100,true);
    }
posted @ 2010-03-05 13:43  RobinLao  阅读(966)  评论(0编辑  收藏  举报