您的位置:首页 > 其它

code-水仙花数

2009-08-11 11:17 169 查看
//打印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方法的通用性
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: