//之所以长,一是因为这个版本比上一个版本改进使用了long类型,二
//是因为这个版本由于位数的增加,时间上出现明显延时,运行一次感
//觉等待的时间变长了。

//打印<=19位(long)的水仙花数

public class Narcissus {
    public static void Main(string[] cmd){
        if ( cmd.Length < 1){
            System.Console.WriteLine("this is [long] Data type " +
                        "Implementation, \nit supports up to [19] " +
                        "digit(that is, the dis [3,19])"
                        );
            System.Console.WriteLine("\nUsage : Narcissus2 <digits>");
        }
        else{
            // 参数异常还未进行判断。
            // if (IsInt(cmd[0])){
                DoIt(int.Parse(cmd[0]));
            // }
        }
    }   
    // check if a string value is integer number
    // static bool IsInt(string strNum){
        // int ix = 0;
        // bool blnReturn = true;
        // while (ix < strNum.Length){
            // if(!System.Char.IsDigit(strNum[ix])){
                // blnReturn = false;
            // }
        // }
        // return blnReturn;
    // }
    //just do it
    static void DoIt(int intDigits){       
        long low  = Pow(10,intDigits-1);
        long high = Pow(10,intDigits);       
        long ix = low;    
        while (ix < high){
            if(IsNarc(ix,intDigits)){
                System.Console.Write(ix + "\t");
            }
            ix++;           
        }
    }
    //long support digits implementation, 19 digits
    static bool IsNarc(long lngNum,int intDigits){
        long lngPlace = 0;          //位上的数码
        long lngPlaceWeight = 1;    //位权
        long lngSum = 0;            //位上的数码的立方的和。
        long lngTemp = lngNum;
        while (lngTemp > 0){           
            lngPlace = (lngNum % (lngPlaceWeight*10))/lngPlaceWeight;                     
            lngPlaceWeight *= 10;
            lngTemp /= 10;
            lngSum += Pow(lngPlace,intDigits);        
        }       
        return lngSum == lngNum;
    }
    //long implementation
    static long Pow(long lngBase, long lngExponent){
        long lngProduct = 1;
        long ix = 0;
        ////treat 0^0 = 1, omit the handling of that condition
        //if (intBase == 0){               
        //    throw new Exception("the base can not be 0");
         //}
        while(ix < lngExponent){
            lngProduct *= lngBase;
            ix++;
        }
        return lngProduct;
    }
}

//写完了后经过简单的测试后发现,这个程序存在严重的性能问题。在算6位时还算
//正常,但到了7位就开始明显看到延迟了。经过简单分析(单独调用),觉得
//IsNarc()的时间开销并不大,主要的时间花销都用在了DoIt()中的循环,但似乎,
//这个个循环没有什么改进的。
//我暂时还没有解决方案。。。。

posted on 2009-08-11 19:16  qinghao  阅读(332)  评论(2编辑  收藏  举报

Copyright © 2009 qinghao Powered by: 博客园