code水仙花数

//打印3位的水仙花数

public class Narcissus {
    public static void Main(string[] cmd){
        //System.Console.WriteLine(Pow(10,0));
        //System.Console.WriteLine(Pow(10,1));
        DoIt(3);
    }
    static void DoIt(int intDigits){
        int low  = (int)Pow(10,intDigits-1);
        int high = (int)Pow(10,intDigits);
        int ix = low;
        while (ix < high){
            if(IsNarc(ix)){
                System.Console.Write(ix + "\t");
            }
            ix++;
            //System.Console.Write(ix +"is not "+ "\t");
        }
    }
    //3 digits implementation
    static bool IsNarc(int intNum){
        int units = 0;
        int tens  = 0;
        int hundreds = 0;
        units    = (intNum % (int)Pow(10,1)) / (int)Pow(10,0);
        tens     = (intNum % (int)Pow(10,2)) / (int)Pow(10,1);
        hundreds = (intNum % (int)Pow(10,3)) / (int)Pow(10,2);
        return intNum==(Pow(units,3)+Pow(tens,3)+Pow(hundreds,3));
    }
    //integer implementation only
    static long Pow(int intBase, int intExponent){
        long product = 1;
        int 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 < intExponent){
            product *= intBase;
            ix++;
        }
        return product;
    }
}

//理论上,最大的水仙花数不超过34位。
//思考:如何把全部的水仙花数打印完。
//要解决的问题
//1. 数太大(考虑自己构造数据类型)
//2. IsNarc方法的通用性

原文地址:https://www.cnblogs.com/qinghao/p/1543472.html