浙大版《C语言程序设计(第3版)》题目集
习题4-6 水仙花数 (20 分)
水仙花数是指一个N位正整数(N≥3),它的每个位上的数字的N次幂之和等于它本身。例如:153=13+53+33。 本题要求编写程序,计算所有N位水仙花数。
输入格式:
输入在一行中给出一个正整数N(3≤N≤7)。
输出格式:
按递增顺序输出所有N位水仙花数,每个数字占一行。
输入样例1:
3
输出样例1:
153
370
371
407
二、题解
不要用pow
函数求xn,会超时,用循环来求。循环耗时480ms左右,用pow
直接TLE。
思路很粗暴,给出n,先求出开始和结尾的数,如n = 3, start = 100, end = 999;这部分可以用if解决,然后直接进行暴力枚举。对每一个数x进行拆分,求解出x每一个位数m的n次幂,累加后与x对比。注意如果用while循环求mn时,循环结束n = -1,需要对n进行恢复,否者在第二个循环会出现死循环。
c代码
#include <stdio.h>
int P(int n) { //求end的值
int ed = 0, temp = 9;
while(n--) ed = ed * 10 + temp;
return ed;
}
int split(int x, int n) {
int ct = n, temp = 0, t = x;
while(x) { //求x每一位的n次方之和
int c = 1;
while(n--) c *= (x % 10); //求(x%10)的n次方
n = ct; //n恢复
temp += c; //累加
x /= 10;
}
if(temp == t) return 1; //比较,若等于返回真
return 0;
}
int main() {
int n;
scanf("%d", &n);
int c = n;
int st = 1;
while(n--) st *= 10; //求start的值
st /= 10;
n = c; //对n进行恢复
int ed = P(n); //求end的值
for (int i = st; i <= ed; i++) {
if(split(i, n)) printf("%d\n", i);
}
return 0;
}