水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。(例如:1^3 + 5^3 + 3^3 = 153)
初步代码:
int nMax = 9999999;
int nResult[9999];
int nCount = 0;
for( int i = 0; i < nMax; i++ )
{
if( i < 10 )
{
if( i == i * i * i )
{
nResult[nCount] = i;
nCount++;
}
}
else if( i < 100 )
{
int nG = i % 10;
int nS = i / 10 % 10;
if( i == nG * nG * nG + nS * nS * nS )
{
nResult[nCount] = i;
nCount++;
}
}
else if( i < 1000 )
{
int nG = i % 10;
int nS = i / 10 % 10;
int nB = i / 100 % 10;
if( i == nG * nG * nG + nS * nS * nS + nB * nB * nB )
{
nResult[nCount] = i;
nCount++;
}
}
else if( i < 10000 )
{
int nG = i % 10;
int nS = i / 10 % 10;
int nB = i / 100 % 10;
int nQ = i / 1000 % 10;
if( i == nG * nG * nG * nG + nS * nS * nS * nS + nB * nB * nB * nB + nQ * nQ * nQ * nQ)
{
nResult[nCount] = i;
nCount++;
}
}
else if( i < 100000 )
{
int nG = i % 10;
int nS = i / 10 % 10;
int nB = i / 100 % 10;
int nQ = i / 1000 % 10;
int nW = i / 10000 % 10;
if( i == nG * nG * nG * nG * nG + nS * nS * nS * nS * nS + nB * nB * nB * nB * nB + nQ * nQ * nQ * nQ * nQ \
+ nW * nW * nW * nW * nW )
{
nResult[nCount] = i;
nCount++;
}
}
else if( i < 1000000 )
{
int nG = i % 10;
int nS = i / 10 % 10;
int nB = i / 100 % 10;
int nQ = i / 1000 % 10;
int nW = i / 10000 % 10;
int nSW = i /100000 % 10;
if( i == nG * nG * nG * nG * nG * nG +
nS * nS * nS * nS * nS * nS +
nB * nB * nB * nB * nB * nB +
nQ * nQ * nQ * nQ * nQ * nQ +
nW * nW * nW * nW * nW * nW +
nSW * nSW * nSW * nSW * nSW * nSW )
{
nResult[nCount] = i;
nCount++;
}
}
else if( i < 10000000 )
{
int nG = i % 10;
int nS = i / 10 % 10;
int nB = i / 100 % 10;
int nQ = i / 1000 % 10;
int nW = i / 10000 % 10;
int nSW = i /100000 % 10;
int nBW = i /1000000 % 10;
if( i == nG * nG * nG * nG * nG * nG * nG +
nS * nS * nS * nS * nS * nS * nS +
nB * nB * nB * nB * nB * nB * nB +
nQ * nQ * nQ * nQ * nQ * nQ * nQ +
nW * nW * nW * nW * nW * nW * nW +
nSW * nSW * nSW * nSW * nSW * nSW * nSW+
nBW * nBW * nBW * nBW * nBW * nBW * nBW )
{
nResult[nCount] = i;
nCount++;
}
}
}
CString str;
for( int j = 0; j < nCount; j++ )
{
CString strTmp;
strTmp.Format ( "%d\r\n", nResult[j] );
str += strTmp;
}
AfxMessageBox( str );
}
显然,上面的代码略显蠢笨,就像笨勤的郭靖,但却很认真。当然,如果要快速求出5位数以内的所有水仙花数,上面上家是最简单也是最快的。
但是,如果要判断任意一个整数是否是水仙花数,就不是很适用了。参考如下代码,由百度得到(我进行了整理,调试和存在的问题的修改):
long n;
long p;
long c,a,j,s[30],i,q;
p=0;
a=10;
scanf("%d",&n);
q=n;
c = n; //JQB ADD
//计算出位数
for(i=1;c>10 ;++i)
{
c=n/a;
a=a*10;
}
printf("i=%d,a=%d \n",i,a);
//得到每一位数,并依次放入数组中
for (j=1;a>=10 ;++j)
{
s[j]=n/(a/10);
n=n-s[j]*(a/10);
a=a/10;
printf("j=%d,a=%d\n",j,a);
}
//计算n位数的每一位的n次方的和
for (j=1;j<=i ;j++)
{
p+=pow(s[j],i);printf("p=%d,i=%d\n",p,i);
}
if (p==q)
{
printf("%d 为水仙花数",q);
}
else
{
printf("%d 该数不是水仙花数",q);
}