JAVA-水仙花数


7-1 JAVA-水仙花数 (14 分)
水仙花数是指一个N位正整数(7≥N≥3),它的每个位上的数字的N次幂之和等于它本身。例如:153=13+53+33。 要求编写程序,计算所有N位水仙花数。

输入格式:
输入一个正整数N(3≤N≤7)。

输出格式:
按递增顺序输出所有N位水仙花数,每个数字占一行。

输入样例:
在这里给出一组输入。例如:

3
输出样例:
在这里给出相应的输出。例如:

153
370
371
407

import java.util.Scanner;
import static java.lang.Math.*;
//方法一 该方法会导致运行超时,不建议使用,初学者实力有限目前没办法解决,欢迎大神来评论区交流
public class test1 {
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        int N=sc.nextInt();
        sc.close(); //关闭Scanner对象
        int num[]=new int[N];
        int a=(int) pow(10,N-1);
        int b=(int) pow(10,N);
        for(int i = a; i<b; i++)
        {
            int sum=0;
            for(int j=0;j<N;j++)
            {
                num[j]=(int)(i/pow(10,j)%10);
                sum+=(int)pow(num[j],N);
            }
            if(sum==i)
                System.out.println(i);
        }
    }
}

//方法二
import java.util.Scanner;
import static java.lang.Math.pow;

public class test2 {
  public static void main(String[] args)
  {
      Scanner sc=new Scanner(System.in); 
      int N=sc.nextInt(); 
      sc.close();  //关闭Scanner对象
      int num[]=new int[N];
      int a=(int) pow(10,N-1);
      int b=(int) pow(10,N);
      for(int i = a; i<b; i++)
      {
          int l=i;
          int sum=0;
          for(int j=0;j<N;j++)
          {
              int c=1;
              for (int k = 0; k < N; k++) //遍历n位数
              {
                  c=c*(l%10);  //计算某位数的n次方
              }
              sum+=c;
              l=l/10;
          }
          if(sum==i)
              System.out.println(i);
      }
  }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM