求n位数中有哪些水仙花数
水仙花数是指一个N位正整数(N>=3),它的每个位上的数字的N次幂之和等于它本身。
例如:
153 = 1^3 + 5^3+ 3^3.
1634 = 1^4 + 6^4 + 3^4 + 4^4.
要求计算所有N位水仙花数,n由自己输入,按从小到大的顺序输出水仙花数, 每个数一行;最后输出一个整数, 代表水仙花数的个数.
输入样例 1
3
输出样例 1
153
370
371
407
4
c++代码如下
#include<iostream>
using std::cin;
using std::cout;
using std::endl;
bool IsNarcissisticNumber(int num, int n) {
int s = num, t = 0;
while (num) {
int temp = 1;
for (int i = 0; i < n; i++) {
temp *= (num % 10);
}
t += temp;
num /= 10;
}
return t == s;
}
int main()
{
int n, max=1, min=1, count=0;
cin >> n;
for (int i = 1; i < n; i++) {
min *= 10;
}
max = min * 10;
for (int i = min; i < max; i++) {
if (IsNarcissisticNumber(i, n)) {
cout << i << endl;
count++;
}
}
cout << count << endl;
return 0;
}
浙公网安备 33010602011771号