JAVA-水仙花数
水仙花数是指一个N位正整数(7≥N≥3),它的每个位上的数字的N次幂之和等于它本身。例如:153=13+53+33。 要求编写程序,计算所有N位水仙花数。
输入格式:
输入一个正整数N(3≤N≤7)。
输出格式:
按递增顺序输出所有N位水仙花数,每个数字占一行。
输入样例:
在这里给出一组输入。例如:
3
输出样例:
在这里给出相应的输出。例如:
153
370
371
407
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a=(int)Math.pow(10, n-1);
int b=(int)Math.pow(10, n);//在[a,b)这个范围内取值
for (int i = a; i < b; i++) {
int c=i;
int sum=0;//各位上的数之和
for (int j = 0; j < n; j++)//n个位上的数都执行一遍
{
int r=1;
for (int k = 0; k < n; k++) //某个位上数的n次方
{
r=r*(c%10);
}
sum=sum+r;
c=c/10;
}
if(sum==i)
System.out.print(i+" ");
}
}
}
结果显示:
3
153 370 371 407
538

被折叠的 条评论
为什么被折叠?



