找不到思路。水仙花
输入一个3到7的正整数n,输出所有n为数的水仙花数。比如输入3,就会输出3位的水仙花数。。。想了好久都找不到什么思路。。。求助。。。
2016-10-18 22:52

2016-10-19 05:50
2016-10-19 12:51

2016-10-19 14:51
程序代码:#include <stdio.h>
void foo( unsigned n )
{
static unsigned long long table[11][11] = { 0 };
if( table[0][0] == 0 )
{
for( size_t i=0; i!=sizeof(table)/sizeof(*table); ++i )
{
unsigned long long t = 1;
for( size_t j=0; j!=sizeof(*table)/sizeof(**table); ++j, t*=i )
table[i][j] = t;
}
}
for( unsigned a=0; a<=n; ++a )
for( unsigned b=0; b<=n-a; ++b )
for( unsigned c=0; c<=n-a-b; ++c )
for( unsigned d=0; d<=n-a-b-c; ++d )
for( unsigned e=0; e<=n-a-b-c-d; ++e )
for( unsigned f=0; f<=n-a-b-c-d-e; ++f )
for( unsigned g=0; g<=n-a-b-c-d-e-f; ++g )
for( unsigned h=0; h<=n-a-b-c-d-e-f-g; ++h )
for( unsigned i=0; i<=n-a-b-c-d-e-f-g-h; ++i )
{
unsigned long long sum = a*table[1][n] + b*table[2][n] + c*table[3][n] + d*table[4][n] + e*table[5][n] + f*table[6][n] + g*table[7][n] + h*table[8][n] + i*table[9][n];
if( sum >= table[10][n-1] )
{
unsigned buf[10] = { 0, a, b, c, d, e, f, g, h, i };
for( unsigned long long s=sum; s; s/=10 )
--buf[s%10];
if( buf[1]==0 && buf[2]==0 && buf[3]==0 && buf[4]==0 && buf[5]==0 && buf[6]==0 && buf[7]==0 && buf[8]==0 && buf[9]==0 )
printf( " %llu\n", sum );
}
}
}
int main( void )
{
puts("3位水仙花有:"); foo(3);
puts("4位水仙花有:"); foo(4);
puts("5位水仙花有:"); foo(5);
puts("6位水仙花有:"); foo(6);
puts("7位水仙花有:"); foo(7);
puts("8位水仙花有:"); foo(8);
puts("9位水仙花有:"); foo(9);
puts("10位水仙花有:"); foo(10);
return 0;
}
2016-10-19 15:31
程序代码:#include<iostream>
#include <cmath>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
long n1, n2, a;
int i;
cout << "请输入Narcissistic number的位数:" << endl;
cin >> i;
cout << i << "位数的Narcissistic number包括:" << endl;
for (n1 = pow(10, i - 1); n1 < pow(10, i); n1++)
{
n2 = 0;
for (int j=0; j < i; j++)
{
a = pow(10, j);
a = n1 / a;
a = a % 10;
a = pow(a, i);
n2 = n2 + a;
}
if (n1 == n2)
cout << n1 << endl;
}
return 0;
}
2016-10-19 15:33
2016-10-19 16:36
2016-10-19 16:45
2016-10-19 16:45
2016-10-19 16:45