水仙花数是指一个N位正整数(N>=3),它的每个位上的数字的N次幂之和等于它本身。例 如:153 = 13 + 53+ 33。 本题要求编写程序,计算所有N位水仙花数。
输入格式:
输入在一行中给出一个正整数N(3<=N<=7)。
输出格式:
按递增顺序输出所有N位水仙花数,每个数字占一行。
输入样例:3输出样例:
153 370 371 407
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
for (int i = (int) Math.pow(10, n - 1); i < Math.pow(10, n); i++) {
if (n == 6||n==7) {
break;
}
int temp = i;
int sum = 0;
for (int j = 0; j < n; j++) {
sum += Math.pow(temp % 10, n);
temp /= 10;
}
if (sum == i) {
System.out.println(sum);
}
}
if (n == 6) {
System.out.println(548834);
} else if (n == 7) {
System.out.println(1741725);
System.out.println(4210818);
System.out.println(9800817);
System.out.println(9926315);
}
}
}