水仙花数是指一个 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 ( "%drn", 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);//得到每一位数,并依次放入数组中相关知识
每日经典算法题(三) 求水仙花数
判断一个数是否为“水仙花数“,所谓“水仙花数“是指一个三位数其各位数字的立方和等于该数本身。 例如:371是一个“水仙花数“,371=3^3+7^3+1^3。
C语言:输出所有的水仙花数
水仙花数
打印“水仙花数”
C++: 水仙花数
3497. 水仙花数
打印水仙花数
Python 水仙花数练习
3.水仙花数
网址: 小算法 : 水仙花数 https://m.huajiangbk.com/newsview379202.html
上一篇: 樱桃树种植方法 |
下一篇: 求自制创意水龙头的方法步骤 |